当前位置:首页 » 程序代码 » 正文

获取状态栏,导航栏的高度

有2种方式来获取状态栏和导航栏的高度。

一、在 Ability 中获取并全局存储,然后在页面调用。

适用于需要多次调用高度的场景,通过 PersistentStorage 存储获取结果:

// EntryAbility.ets
import { window, common } from '@kit.ArkUI';

onWindowStageCreate(windowStage: window.WindowStage) {
     windowStage.getMainWindow().then((win) => {
      // 获取系统规避区域
      const systemArea1 = win.getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM);
      const systemArea2 = win.getWindowAvoidArea(window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR);
      const statusBarHeight = systemArea1.topRect.height; // 状态栏高度(px)
      const navBarHeight = systemArea2.bottomRect.height; // 导航栏高度(px)//源码来自wb98.com

      // 存储到全局变量(需先定义PersistentStorage)
      PersistentStorage.PersistProp('statusBarHeight', px2vp(statusBarHeight));
      PersistentStorage.PersistProp('navBarHeight', px2vp(navBarHeight));
  });
}


在页面中通过 AppStorage.get 使用存储值:

@Entry
@Component
struct Index {

  // 页面组件内调用
  @StorageLink('statusBarHeight') statusBarHeight: number = 0;
  @StorageLink('navBarHeight') navBarHeight: number = 0;

  build() {
    Column() {

      Text(this.statusBarHeight.toString()) //状态栏高度
      Text(this.navBarHeight.toString())   //导航栏高度

    }
  }
}


二、在 UI 组件中动态获取

适用于单次获取的场景:

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

@Entry
@Component
struct Index {
  @State height1: number = 0
  @State height2: number = 0

  build() {
    Column() {

      Text(this.height1.toString())
      Text(this.height2.toString())

      Button('获取高度')
        .onClick(() => {
          window.getLastWindow(getContext(this)).then((win) => {
            const systemArea1 = win.getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM);
            const systemArea2 = win.getWindowAvoidArea(window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR);
            const statusBarHeight = px2vp(systemArea1.topRect.height); //状态栏高度
            const navBarHeight = px2vp(systemArea2.bottomRect.height); //导航栏高度 //源码来自wb86.com

            this.height1 = statusBarHeight
            this.height2 = navBarHeight
            // this.height2 = navBarHeight > 0 ? navBarHeight : statusBarHeight //导航栏高度有时获取的值为0,就赋值状态栏一样的数值。

          });
        })
    }
  }
}


打赏 支付宝打赏 微信打赏

来源:济亨网

本文链接:https://www.wb98.com/post/387.html

arkts  鸿蒙  
    << 上一篇 下一篇 >>

    湘公网安备 43011102000514号 - 湘ICP备08100508号