示例实现页面按需沉浸式布局封装 utils/windowManager.ets ,使用该示例需考虑不同设备的避让区,并对安全区布局进行调整。通过window.getLastWindow 获取当前窗口对象 ,window.setWindowLayoutFullScreen 设置主窗口或子窗口的布局是否为沉浸式布局 ,getWindowAvoidArea 使用窗口对象获取某一个区域的尺寸。
import { window } from '@kit.ArkUI'
import { BusinessError } from '@kit.BasicServicesKit';
export class windowManager {
// 是否开启沉浸式
static isFullScreen(isOpen:boolean){
// 获取当前页面 并且设置为全屏显示(沉浸式显示模式)
// getContext 获取上下文
window.getLastWindow(getContext()).then(win=>{
win.setWindowLayoutFullScreen(isOpen)
if(isOpen){
// getAvoidAreaHeight
let type1 = window.AvoidAreaType.TYPE_SYSTEM;
let type2 = window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR;
window.getLastWindow(getContext()).then((data) => {
// 获取系统默认区域,一般包括状态栏、导航栏
let avoidArea1 = data.getWindowAvoidArea(type1);
// 顶部状态栏高度
let statusBarHeight = px2vp(avoidArea1.topRect.height);
// 底部导航栏高度
let bottomNavHeight = px2vp(avoidArea1.bottomRect.height);
// 获取导航条区域
let avoidArea2 = data.getWindowAvoidArea(type2);
// 获取到导航条区域的高度
let indicatorHeight = px2vp(avoidArea2.bottomRect.height);
console.info(`屏幕顶部状态栏 statusBarHeight = ${statusBarHeight}`);
console.info(`底部导航栏 bottomNavHeight = ${bottomNavHeight}`);
console.info(`导航条的高度 indicatorHeight = ${indicatorHeight}`);
// 存储AvoidAreaHeight,方便给其他组件使用
AppStorage.setOrCreate('statusBarHeight', statusBarHeight)
AppStorage.setOrCreate('bottomNavHeight', bottomNavHeight)
AppStorage.setOrCreate('indicatorHeight', indicatorHeight)
}).catch((err: BusinessError) => {
console.error(`获取屏幕顶部状态栏、底部导航栏和导航条的高度 出现异常 Failed to obtain the window. Cause: ${JSON.stringify(err)}`);
});
}else{
AppStorage.setOrCreate('statusBarHeight', 0)
AppStorage.setOrCreate('bottomNavHeight', 0)
AppStorage.setOrCreate('indicatorHeight', 0)
}
})
}
// 改变状态栏文字颜色
static changeColor(color:string){
window.getLastWindow(getContext())
.then(win=>{
win.setWindowSystemBarProperties({statusBarContentColor:color})
})
.catch((err: BusinessError) => {
console.error(`改变安全区文字颜色失败: ${JSON.stringify(err)}`);
});
}
// 设置状态栏背景颜色
static setStatusBarColor(color: string) {
window.getLastWindow(getContext())
.then(win => {
// 设置状态栏颜色(具体API名称可能因系统版本而异)
win.setWindowSystemBarProperties({
statusBarColor: color,
statusBarContentColor: '#000000' // 文字颜色(深色)
});
})
.catch((err: BusinessError) => {
console.error(`设置状态栏颜色失败: ${JSON.stringify(err)}`);
});
}
}
沉浸式页面实现:
https://developer.huawei.com/consumer/cn/doc/best-practices/bpta-immersive#section1052895593418
安全区域:
本页作者:czhdawn,如若转载,请注明出处:https://www.czhdawn.cn/archives/4830