HarmonyOS 获取屏幕宽度和导航栏高度为0?

onWindowStageCreate(windowStage: window.WindowStage): void {
  // Main window is created, set main page for this ability
  hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
  // this.setFullSize(windowStage);
  windowStage.loadContent('pages/PianoPage', this.localStorage, (err) => {
  if (err.code) {
  hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
  return;
}

let windowClass: window.Window = windowStage.getMainWindowSync(); // 获取应用主窗口
CommonConstants.WINDOW_WIDTH = windowClass.getWindowProperties().windowRect.width / display.getDefaultDisplaySync().densityPixels;
let area = windowClass.getWindowAvoidArea(window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR);
CommonConstants.NAV_HEIGHT = area.bottomRect.height / display.getDefaultDisplaySync().densityPixels;
// 1. 设置窗口全屏
let isLayoutFullScreen = true;
windowClass.setWindowLayoutFullScreen(isLayoutFullScreen)
  .then(() => {
    console.info('Succeeded in setting the window layout to full-screen mode.');
  })
  .catch((err: BusinessError) => {
    console.error('Failed to set the window layout to full-screen mode. Cause:' + JSON.stringify(err));
  });


// 2. 设置状态栏和导航条隐藏
windowClass.setSpecificSystemBarEnabled('status', false)
  .then(() => {
    console.info('Succeeded in setting the status bar to be invisible.');
  })
  .catch((err: BusinessError) => {
    console.error(`Failed to set the status bar to be invisible. Code is ${err.code}, message is ${err.message}`);
  });
});
}

如上函数,跳转到一个UIAbility,在他的onWindowStageCreate函数下执行上述操作,得到的 CommonConstants.WINDOW\_WIDTH 和CommonConstants.NAV\_HEIGHT有概率为0,特别是折叠屏全部展开的状态下。

如何才能准确获取屏幕高宽值,和导航栏高度

阅读 485
1 个回答

宽高:

display.getAllDisplays((err, data) => {
  let screenWidth : number = data[0].width
  let screenHeight : number = data[0].height
  console.log('width = ' + screenWidth + 'height = ' + screenHeight)
  console.log('width +  height = ' + JSON.stringify(data))
})

导航栏:

let windowClass: window.Window = windowStage.getMainWindowSync(); // 获取应用主窗口
let type = window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR; // 以导航条避让为例
let avoidArea = windowClass.getWindowAvoidArea(type);
let bottomRectHeight = avoidArea.bottomRect.height; // 获取到导航条区域的高度
console.log("bottomRectHeight: " + bottomRectHeight)
let area = windowClass.getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM);
let statusBarHeight = px2vp(area.topRect.height) //状态栏高度
console.log("statusBarHeight: " + statusBarHeight)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进