在HarmonyOS中如何监听获取安全区域高度?

阅读 551
1 个回答

通过window模块的on('avoidAreaChange')方法开启当前窗口系统规避区变化的监听,获取内容可视区域大小,同时也可以监听软键盘的弹出收起。开发者可以根据软键盘弹出之后的可视区域大小去动态的调整布局中组件的高度去适配界面。

import { window } from '@kit.ArkUI';

@Entry
@Component
struct GetSafeAreaHeightDemo {
  @State screenHeight: number = 0; // 安全区域高度
  @State isKeyBoardHidden: boolean = false; // 软键盘是否隐藏

  aboutToAppear(): void {
    window.getLastWindow(getContext(this)).then(currentWindow => {
      let property = currentWindow.getWindowProperties();
      let avoidArea = currentWindow.getWindowAvoidArea(window.AvoidAreaType.TYPE_KEYBOARD);
      // 初始化显示区域高度
      this.screenHeight = px2vp(property.windowRect.height - avoidArea.topRect.height - avoidArea.bottomRect.height);
      // 开启当前窗口系统规避区变化的监听
      currentWindow.on('avoidAreaChange', data => {
        if (data.type !== window.AvoidAreaType.TYPE_KEYBOARD) {
          return;
        }
        if (data.area.bottomRect.height <= 0) {
          this.isKeyBoardHidden = true;
        } else {
          this.isKeyBoardHidden = false;
        }
        this.screenHeight = px2vp(property.windowRect.height -data.area.topRect.height - data.area.bottomRect.height);
        console.info(`screen height is: ${this.screenHeight}`);
      })
    })
  }

  build() {
    Column() {
      TextInput()
    }
  }
}

本文参与了 【 HarmonyOS NEXT 技术问答冲榜,等你来战!】欢迎正在阅读的你也加入。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题