HarmonyOS 鸿蒙Next如何获取顶部状态栏的高度
HarmonyOS 鸿蒙Next如何获取顶部状态栏的高度
如何获取顶部状态栏的高度,指南中只有获取到底部导航的示例,没有获取到顶部状态栏高度的示例
3 回复
当前window提供API获取系统区域包括导航栏和状态栏。
API:getWindowAvoidArea
示例代码:
window.getLastWindow(getContext(this), (error, topWindow) => {
if (topWindow) {
let area = topWindow.getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM);
//注意:返回的是px值,如果要用vp值需要转换
this.statusBarHeight = px2vp(area.topRect.height);
this.naviBarHeight = px2vp(area.bottomRect.height);
}
});
参考链接:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V13/js-apis-window-V13
说明:示例代码中window.AvoidAreaType.TYPE_SYSTEM仅为举例,目前一共有5种枚举类型,看你自己的需求,以文档为基准使用。
更多关于HarmonyOS 鸿蒙Next如何获取顶部状态栏的高度的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
windowStage.getMainWindowSync()
.getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM).topRect.height
HarmonyOS 鸿蒙Next如何获取顶部状态栏的高度方法如下
import { window } from '@kit.ArkUI'; // 导入ArkUI的window模块
import { common } from '@kit.AbilityKit'; // 导入AbilityKit的common模块
export class AppUtil {
private static windowStage: window.WindowStage; // 静态变量,用于存储窗口管理器
private static context: common.UIAbilityContext; // 静态变量,用于存储UIAbility的上下文信息
/**
* 初始化方法,缓存全局变量,在UIAbility的onWindowStageCreate方法中调用该方法进行初始化。
* Initialization method, caches global variables, call this method in the onWindowStageCreate method of UIAbility for initialization.
* @param context 上下文
* @param windowStage 窗口管理器
*/
static init(context: common.UIAbilityContext, windowStage: window.WindowStage) {
AppUtil.context = context; // 初始化上下文
AppUtil.windowStage = windowStage; // 初始化窗口管理器
}
/**
* 获取主窗口
* Get the main window
*/
static getMainWindow(): window.Window {
if (!AppUtil.windowStage) { // 如果窗口管理器未初始化
console.error("windowStage为空,请在UIAbility的onWindowStageCreate方法中调用AppUtil的init方法进行初始化!WindowStage is null, please call the init method of AppUtil in the onWindowStageCreate method of UIAbility for initialization!");
}
return AppUtil.windowStage.getMainWindowSync(); // 同步获取主窗口
}
/**
* 获取状态栏的高度,单位为px。
* Get the height of the status bar, with the unit in pixels.
* @returns 返回状态栏的高度,单位为px。
* Returns the height of the status bar, in pixels.
*/
static getStatusBarHeight(): number {
try {
// 获取主窗口
let windowClass = AppUtil.getMainWindow();
// 获取系统避免区域,通常包含状态栏
let avoidArea = windowClass.getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM);
// 返回状态栏的高度
return avoidArea.topRect.height;
} catch (err) {
// 捕获异常并使用日志工具打印错误信息
console.error(JSON.stringify(err));
// 发生异常时返回0
return 0;
}
}
}

