鸿蒙工具类---设置全屏效果(上下安全区背景可设置)
1,获得上下文对象(context)
在EntryAbility.ets文件中的onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {}方法中,通过
AppStorage.setOrCreate('context', this.context)
将上下文对象存储起来 - this.context。
2,创建工具类,设置上下安全区(顶部状态栏,底部安全区域)
import { window } from '@kit.ArkUI' import { logger } from './Logger' // 实时更新一下导入位置class FullScreen {// 开启全屏async enable () {// 1. 先获取上下文对象const context = AppStorage.get<Context>('context')if (context) {// 2. 获取应用窗口const win = await window.getLastWindow(context)// 3. 开启沉浸式模式/全屏效果await win.setWindowLayoutFullScreen(true)// 4. 获取顶部区域const topArea = win.getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM)// 5. 存储顶部状态栏的高度 默认获取的高度单位是px// px2vp() -> 将px单位的数值 -> vp单位 精准logger.info('顶部状态的高度', px2vp(topArea.topRect.height).toString())AppStorage.setOrCreate('topHeight', px2vp(topArea.topRect.height))// 6. 获取底部区域const bottomArea = win.getWindowAvoidArea(window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR)// 7. 存储顶部状态栏的高度 默认获取的高度单位是px// px2vp() -> 将px单位的数值 -> vp单位 精准logger.info('底部安全区的高度', px2vp(bottomArea.bottomRect.height).toString())AppStorage.setOrCreate('bottomHeight', px2vp(bottomArea.bottomRect.height))}}// 关闭全屏async disable() {// 1. 先获取上下文对象const context = AppStorage.get<Context>('context')if (context) {// 2. 获取应用窗口const win = await window.getLastWindow(context)// 3. 关闭沉浸式模式/全屏效果await win.setWindowLayoutFullScreen(false)AppStorage.setOrCreate('topHeight', 0)AppStorage.setOrCreate('bottomHeight',0)}} } export const fullScreen = new FullScreen()
3,工具类使用
在EntryAbility.ets文件中的onWindowStageCreate(windowStage: window.WindowStage): void {}方法中进行设置,因为这个方法是页面展示之前会被调用的方法。
fullScreen.enable() //开启全屏 fullScreen.disable() //关闭全屏
4,获取安全区的大小
@StorageProp('topHeight') topHeight: number = 0
@StorageProp('bottomHeight') bottomHeight: number = 0