鸿蒙Next状态栏高度如何获取

在鸿蒙Next开发中,如何获取状态栏的高度?我在文档里没有找到对应的API,尝试通过WindowManager获取时返回的值始终为0。请问是否有官方推荐的方法或示例代码?

2 回复

鸿蒙Next中获取状态栏高度的方法:

  1. 使用WindowManager获取:
import window from '@ohos.window';

let windowClass = null;
window.getTopWindow((err, data) => {
  if (err) {
    console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(err));
    return;
  }
  windowClass = data;
  let avoidArea = windowClass.getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM);
  let statusBarHeight = avoidArea.topRect.height;
  console.info('Status bar height: ' + statusBarHeight);
});
  1. 通过系统能力获取:
import display from '@ohos.display';

let display = display.getDefaultDisplaySync();
let statusBarHeight = display.cutout?.safeArea?.top || 0;

注意:需要在module.json5中申请ohos.permission.SYSTEM_FLOAT_WINDOW权限。建议在页面onShow生命周期中调用,确保窗口已创建。

更多关于鸿蒙Next状态栏高度如何获取的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在鸿蒙Next(HarmonyOS NEXT)中,获取状态栏高度可以通过以下方法实现:

方法一:使用系统API(推荐)

通过Window类获取窗口的topWindow,并从中提取状态栏高度。

import window from '@ohos.window';

// 获取状态栏高度
async function getStatusBarHeight(): Promise<number> {
  try {
    const windowClass = await window.getLastWindow(this.context);
    const windowRect = windowClass.getWindowProperties().windowRect;
    const statusBarHeight = windowRect.top; // 状态栏高度为窗口顶部到屏幕顶部的距离
    return statusBarHeight;
  } catch (error) {
    console.error('获取状态栏高度失败:', error);
    return 0; // 返回默认值
  }
}

方法二:通过资源查询

resources/base/element/string.json中定义状态栏高度资源,然后在代码中引用。

  1. 资源文件定义
{
  "name": "status_bar_height",
  "value": "40vp"
}
  1. 代码中获取
import resourceManager from '@ohos.resourceManager';

async function getStatusBarHeightFromResource(): Promise<number> {
  try {
    const value = await resourceManager.getStringByName('status_bar_height');
    return parseFloat(value); // 返回数值(单位vp)
  } catch (error) {
    console.error('从资源获取状态栏高度失败:', error);
    return 0;
  }
}

注意事项:

  1. 单位转换:若需要像素值,可使用px2vp/vp2px进行单位转换。
  2. 动态变化:状态栏高度可能随设备或系统设置变化,建议在界面初始化时获取并动态调整布局。
  3. 权限:确保应用具有ohos.permission.SYSTEM_FLOAT_WINDOW权限(若涉及悬浮窗)。

根据实际场景选择合适的方法,推荐优先使用系统API以保持兼容性。

回到顶部