精华 HarmonyOS 鸿蒙Next获取屏幕底部安全区的高度以及获取底部手势指示条高度

发布于 1周前 作者 bupafengyu 最后一次编辑是 5天前 来自 鸿蒙OS

HarmonyOS 鸿蒙Next获取屏幕底部安全区的高度以及获取底部手势指示条高度

这里怎么获取状态栏的高度是0,使用的是mate 60 pro真机

cke_123.png

3 回复

已解决 这个使用错了window.AvoidAreaType.TYPE_SYSTEM,需要再EntryAbility.ets中获取

//获取状态栏高度
let type1 = window.AvoidAreaType.TYPE_SYSTEM; // 以导航条避让为例
let avoidArea1 = windowClass.getWindowAvoidArea(type1);
let topRectHeight = avoidArea1.topRect.height; // 获取到导航条区域的高度
AppStorage.setOrCreate('topRectHeight', topRectHeight);

在HarmonyOS鸿蒙Next中获取状态栏高度,可以通过getWindowAvoidArea方法实现。具体地,你需要先获取当前窗口,然后使用window.AvoidAreaType.TYPE_SYSTEM作为参数调用getWindowAvoidArea,返回的avoidArea.topRect.height即为状态栏高度,单位通常为px。如果状态栏高度与预期不符,请检查窗口是否处于全屏模式,因为全屏模式下状态栏可能会被隐藏。如果问题依旧没法解决请加我微信,我的微信是itying888。

核心代码:

   //  获取布局避让遮挡的区域
      let type = window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR; // 以导航条避让为例
      let avoidArea = windowClass.getWindowAvoidArea(type);
      // 此处获取的单位为px,需转为vp
      let bottomRectHeight = px2vp(avoidArea.bottomRect.height); // 获取到导航条区域的高度
      console.log("bottomRectHeight is " + bottomRectHeight);AppStorage.setOrCreate('bottomRectHeight', bottomRectHeight);

EntryAbility.ets中获取,最后在tab页中将整体页面设置margin({bottom: bottomRectHeight})即可。

  onWindowStageCreate(windowStage: window.WindowStage): void {
    // Main window is created, set main page for this ability
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
    // 沉浸式状态栏
    let windowClass: window.Window | undefined = undefined;
    windowStage.getMainWindow((err: BusinessError, data) => {
      windowClass=data
      //设置沉浸式状态栏
      let promise = windowClass.setWindowLayoutFullScreen(true);
      promise.then(() => {
        //设置状态栏透明背景
        windowStage.getMainWindowSync().setWindowSystemBarEnable(['status']).then(() => {
          const systemBarProperties: window.SystemBarProperties = {
            statusBarColor: '#00000000'
          };
          //设置窗口内导航栏、状态栏的属性
          windowStage.getMainWindowSync().setWindowSystemBarProperties(systemBarProperties)
            .then(() => {
              console.info('Succeeded in setting the system bar properties.');
            }).catch((err:object) => {
            console.error('Failed to set the system bar properties. Cause: ' + JSON.stringify(err));
          });
        })
      }).catch((err: BusinessError) => {
        console.error(`Failed to set the window layout to full-screen mode. Cause code: ${err.code}, message: ${err.message}`);
      });

      //  获取布局避让遮挡的区域
      let type = window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR; // 以导航条避让为例
      let avoidArea = windowClass.getWindowAvoidArea(type);
      // 此处获取的单位为px,需转为vp
      let bottomRectHeight = px2vp(avoidArea.bottomRect.height); // 获取到导航条区域的高度
      console.log("bottomRectHeight is " + bottomRectHeight);AppStorage.setOrCreate('bottomRectHeight', bottomRectHeight);

    })
回到顶部