1)利用方法获取当前的窗口并开启全屏
注意:开启全屏不管是在那个页面触发其他页面都能开启全屏,只需要开启一次(在第一个页面的生命周期函数中执行还能避免开启全屏后跳动的问题),注意顶部的内容直接在顶部显示。
2)设置安全高度并存储到@AppStorage中
让各个页面利用@StorageProp取到安全高度并设置顶部的内边距,避免页面内容在安全区域显示
完整代码:
aboutToAppear(): void {
//利用系统的window 这个API的方法获得了当前的窗口
//ctx: BaseContext这个签名有的放方法是getContext
window.getLastWindow(getContext()).then((win) => {
//设置了全屏,开启了沉浸式模式
win.setWindowLayoutFullScreen(true)
//获取设备的安全高度
let area = win.getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM)
let height = area.topRect.height //这个的单位是px
//将单位转换为VP,这个方法是px转vp
let vpHeight = px2vp(height)
//将获取到的高度存储到AppStorage,让每个tab页面都能拿到这个值
AppStorage.setOrCreate('topHeight', vpHeight)
})
}
tips:实时模板可以可以快速复用已经写过的代码
坑点: 获取的安全高度的单位是px,要用方法px2vp()进行转换为vp后使用
3)设置安全区域文字的颜色
考虑到不同页面的风格,安全区域的风格与之相匹配,在有需要的页面利用生命周期函数aboutToAppear()进行设置,离开页面后利用生命周期函数aboutToDisappear()对已设置的内容进行恢复。
坑点:颜色值不写满6个不识别 (statusBarContentColor: '#FFFFFF'才是白色,颜色值为'#fff'系统不识别,'#000'也不会被识别为黑色)
mine页面文字设置的完整代码:
//进入页面设置
aboutToAppear(): void {
//设置安全区域的文字颜色
window.getLastWindow(getContext())
.then((win) => {
win.setWindowSystemBarProperties({ statusBarContentColor: '#FFFFFF' })
})
}
//离开页面恢复
aboutToDisappear(): void {
//设置安全区域的文字颜色
window.getLastWindow(getContext())
.then((win) => {
win.setWindowSystemBarProperties({ statusBarContentColor: '#000000' })
})
}
4)将设置沉浸式模式个各种方法封装为类windowManager中
使用时直接调用,减少代码冗余,提高代码复用性
封装完整代码:
import { window } from '@kit.ArkUI'
export class windowManager {
//1.开启沉浸式模式
static enableFullScreen() {
window.getLastWindow(getContext())
.then((win) => {
//设置了全屏,开启了沉浸式模式
win.setWindowLayoutFullScreen(true)
//获取设备的安全高度
let area = win.getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM)
let height = area.topRect.height //这个的单位是px
//将单位转换为VP,这个方法是px转vp
let vpHeight = px2vp(height)
//将获取到的高度存储到AppStorage,让每个tab页面都能拿到这个值
AppStorage.setOrCreate('topHeight', vpHeight)
})
}
static disableFullScreen() {
//2.关闭沉浸式模式
window.getLastWindow(getContext())
.then((win) => {
//关闭全屏,关闭沉浸式模式
win.setWindowLayoutFullScreen(false)
//将高度还原
AppStorage.setOrCreate('topHeight', 0)
})
}
//3.设置状态栏文字颜色
static settingBarLight() {
// 设置文字颜色为白色
//设置安全区域的文字颜色
window.getLastWindow(getContext())
.then((win) => {
win.setWindowSystemBarProperties({ statusBarContentColor: '#FFFFFF' })
})
}
static settingBarBlank() {
// 设置文字颜色为黑色
//设置安全区域的文字颜色
window.getLastWindow(getContext())
.then((win) => {
win.setWindowSystemBarProperties({ statusBarContentColor: '#000000' })
})
}
}