HarmonyOS 鸿蒙Next中获取导航高度
HarmonyOS 鸿蒙Next中获取导航高度 怎么动态获取手机底部导航栏的高度,并且兼容小窗模式?
5 回复
windowStage.loadContent('pages/Index', async (err, data) => {
if (err.code) {
return
}
let windowClass: window.Window = windowStage.getMainWindowSync()
// 注册监听函数,动态获取避让区域数据
windowClass.on('avoidAreaChange', (data) => {
if (data.type === window.AvoidAreaType.TYPE_SYSTEM) {
// 顶部状态栏高度
let topRectHeight = data.area.topRect.height
AppStorage.setOrCreate('topRectHeight', topRectHeight)
} else if (data.type == window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR) {
// 底部导航栏高度
let bottomRectHeight = data.area.bottomRect.height
AppStorage.setOrCreate('bottomRectHeight', bottomRectHeight)
}
})
})
更多关于HarmonyOS 鸿蒙Next中获取导航高度的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
学习了
| 特性 | onAreaChange |
getRectangleById |
onSizeChange |
|---|---|---|---|
| 触发时机 | 组件初始化及区域变化时 | 主动调用时 | 布局变化导致尺寸变化时 |
在HarmonyOS Next中,获取导航高度可通过window.getLastWindow()获取当前窗口实例,再调用getWindowAvoidArea(AvoidAreaType.TYPE_NAVIGATION_INDICATOR)方法,返回的AvoidArea中的bottomRect高度即为导航高度。注意需在UIAbility创建完成后调用。
在HarmonyOS Next中,可通过窗口的避让区域获取底部导航栏高度并兼容小窗模式。核心使用 window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR 获取导航指示器区域,并监听 avoidAreaChange 事件动态更新。
import window from '@ohos.window';
@Entry
@Component
struct Demo {
@State navBarHeight: number = 0;
private win: window.Window | null = null;
async aboutToAppear() {
this.win = await window.getLastWindow(getContext(this));
const area = this.win.getWindowAvoidArea(window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR);
this.navBarHeight = area.bottomRect.height;
this.win.on('avoidAreaChange', () => {
const newArea = this.win!.getWindowAvoidArea(window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR);
this.navBarHeight = newArea.bottomRect.height;
});
}
aboutToDisappear() {
this.win?.off('avoidAreaChange');
}
// ... build使用navBarHeight进行避让
}
小窗模式下窗口尺寸变化同样会触发 avoidAreaChange,因此无需额外处理即可自动兼容。bottomRect.height 即为底部导航栏的实时高度(单位vp)。

