1. 概述

窗口模块负责在同一物理屏幕上管理多个界面,可分为系统窗口(如状态栏、导航栏)和应用子窗口(如弹窗、悬浮窗)。在 ArkUI 的 @ohos.window 模块中,开发者可以通过一系列 API 创建、显示、移动、调整、全屏以及监听窗口事件,快速构建灵活的多窗口交互。

2. 创建与查找窗口

  • 创建子窗口

    import { window } from '@kit.ArkUI';
    
    window.create('debugPanel', window.WindowType.TYPE_FLOAT)
      .then(subWindow => {
        // 保存 subWindow 实例后可进一步操作
      });
    
  • 查找已有窗口

    window.find('debugPanel')
      .then(subWindow => { /* … */ });
    
  • 获取最上层窗口

    window.getTopWindow()
      .then(topWin => { /* … */ });
    

3. 窗口常用能力

每个 Window 实例都支持以下方法:

  • show():将窗口显示到屏幕上
  • destroy():销毁窗口并释放资源
  • moveTo(x: number, y: number):移动到指定坐标
  • resetSize(width: number, height: number):调整窗口尺寸
  • setFullScreen(isFull: boolean):切换全屏模式
  • setLayoutFullScreen(isLayoutFull: boolean):布局是否延展到状态栏/导航栏区域
  • setBackgroundColor(color: string):修改背景色
  • loadContent(path: string):加载本地页面
  • on(eventType, callback):监听 windowSizeChangesystemAvoidAreaChangekeyboardHeightChange

4. 实战示例:悬浮调试面板

@Entry @Component struct MainPage {
  private debugWin: window.Window | null = null;

  build() {
    Column({ space: 10 }) {
      Button('打开悬浮调试面板')
        .onClick(() => this.createDebugPanel())
    }
    .padding(20)
  }

  private createDebugPanel() {
    window.create('debugPanel', window.WindowType.TYPE_FLOAT)
      .then(win => {
        this.debugWin = win;
        win.moveTo(50, 600);
        win.resetSize(300, 200);
        win.setBackgroundColor('#00000080');
        win.loadContent('pages/debug');
      });
  }
}

pages/debug.ets 中,可利用 window.on('keyboardHeightChange', …) 动态调整日志区高度,确保在输入法弹起时内容不被遮挡。

5. 键盘避让与事件

  • 获取避让区

    win.getAvoidArea(AvoidAreaType.INPUT)
      .then(area => {
        // area.height:键盘高度
      });
    
  • 监听避让区变化

    win.on('systemAvoidAreaChange', newArea => {
      // 根据 newArea.height 调整布局
    });
    

6. 多窗口通信

  • 通过 window.find('otherId') 获取目标窗口实例,调用其 loadContentsetBackgroundColor 实现跨窗口更新。
  • 也可在全局发布/订阅消息,或通过共享存储同步数据。

7. 性能优化与资源回收

  • 不再使用时务必调用 destroy(),回收渲染资源。
  • 频繁切换请尽量重用窗口实例,通过 show()/hide() 控制可见性。
  • 在页面卸载钩子(如 aboutToDisappear)中关闭子窗口,保证前后端一致。
Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐