目录

How do I implement the feature of closing a floating window through a swipe gesture?

You can achieve the purpose by hiding the floating window in the onBackPress() lifecycle function of the page. The sample code is as follows:

  1. Create a floating window in the onWindowStageCreate method of the EntryAbility.
    onWindowStageCreate(windowStage: window.WindowStage): void {
      // Create application subwindow
      let windowClass: window.Window | undefined = undefined;
      windowStage.createSubWindow('mySubWindow', (err: BusinessError, data) => {
        if (err.code) {
          console.error(`Failed to create the subwindow. Cause code: ${err.code}, message: ${err.message}`);
          return;
        }
        windowClass = data;
        console.info('Succeeded in creating the subwindow. Data: ' + JSON.stringify(data));
        // After the child window is created successfully, set the position, size, and related properties of the child window.
        windowClass.moveWindowTo(300, 300);
        windowClass.resize(200, 200);
        windowClass.setWindowTouchable(true);
        // Load the corresponding target page for the child window.
        windowClass.setUIContent('pages/Index',(err: BusinessError) => {
          if (err.code) {
            console.error(`Failed to load the content. Cause code: ${err.code}, message: ${err.message}`);
            return;
          }
          if (windowClass) {
            windowClass.setWindowBackgroundColor('#64b38c');
          }
        });
        (windowClass as window.Window).showWindow();
      })
      // ...
    }
  2. Use onBackPress to detect the back button press and destroy the subwindow in the page.
    import { window } from '@kit.ArkUI';
    
    @Entry
    @Component
    struct CloseWindowDemo {
      @State message: string = 'Hello World';
    
      onBackPress(): boolean | void {
        console.log('Triggered');
        const subWindow = window.findWindow('mySubWindow');
        if (subWindow) {
          subWindow.destroyWindow();
        }
        return true;
      }
    
      build() {
        RelativeContainer() {
          Text(this.message)
            .id('HelloWorld')
            .fontSize(20)
            .fontWeight(FontWeight.Bold)
            .alignRules({
              center: { anchor: '__container__', align: VerticalAlign.Center },
              middle: { anchor: '__container__', align: HorizontalAlign.Center }
            })
        }
        .height('100%')
        .width('100%')
      }
    }