鸿蒙OS ArkUI 沉浸式导航栏动态获取高度 -- 小白篇
下面展示一些 内联代码片
。
这是一个 沉浸式的样式工具类,这个没什么可说的,copy过去用就可以了
import window from '@ohos.window';
export class ImmersiveUtils {
public static immersive(windowStage: window.WindowStage, config: {
barColor: string,
contentColor: string,
navigationColor: string,
navigatorColor: string
}) {
windowStage.getMainWindow()
.then(win => {
win.setWindowSystemBarProperties({
statusBarColor: config.barColor,
statusBarContentColor: config.contentColor,
navigationBarColor: config.navigationColor,
navigationBarContentColor: config.navigatorColor
});
})
}
}
下面展示一些 主体代码
。
首先在你的EntryAbility或者是你的主入口UIAbility都可以
在onWindowStageCreate里去实现你的沉浸式导航高度获取和存储
onWindowStageCreate(windowStage: window.WindowStage) {
// 设置沉浸式代码
globalThis.windowStage = windowStage;
// 获取主窗口实例 参考API 9
windowStage.getMainWindow()
.then(win => {
// 设置窗口的布局是否为全屏显示状态
win.setWindowLayoutFullScreen(true);
// 获取导航条高度 参考API 9
// 这个方法为返回的是PX像素,需要使用px2vp方法转换一下 参考API 9
let navHeight:number = win.getWindowAvoidArea(window.AvoidAreaType.TYPE_CUTOUT).topRect.height
// 存储高度信息 参考API 9
PersistentStorage.PersistProp('systemBarHeight', navHeight)
})
}
这里是在你的.ets UI页面里去实现的
// 引入工具类方法
import {ImmersiveUtils} from '../Utils/ImmersiveUtils'
@Entry
@Component
struct Login {
// 获取存储的数据信息
// px2vp 这个方法是.ets后缀文件才有的方法 .ts后缀是没有这个方法的
// 为什么使用这个方法上边的代码块有说明,感兴趣的也可以去查查官方的API文档
@StorageLink('systemBarHeight') systemBarHeight: number = 0;
build() {
Column(){
Text('顶部title')
.fontSize(18)
.fontWeight(FontWeight.Bold)
}.padding({top:px2vp(this.systemBarHeight)}).height('100%').width('100%')
}
//设置你的顶部导航栏样式
onPageShow(){
ImmersiveUtils.immersive(globalThis.windowStage, {
barColor: "#00286098",
contentColor: "#ffffff",
navigationColor: "#005d99d6",
navigatorColor: "#ffffff"
});
}
}