HarmonyOS NEXT - 沉浸式工具
·
一.沉浸式窗口安全区域
💡 Tips:方法一:调用主窗口
这个接口适用两种场景:
1》在onWindowStageCreate 中,获取应用启动时的初始布局避让区域时可调用接口
2》当应用内子窗口需要临时显示,对显示内容做布局避让时可调用该窗口。
- devicInfo 提供终端设备信息
-
window窗口
设置在应用的主页面的entryability
//entryability /onWindowStageCreate //设置全屏 const win = windowStage.getMainWindowSync() win.setWindowLayoutFullScreen(true) //在应用中存储顶部安全高度 const top = win.getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM).topRect AppStorage.setOrCreate<number>(SafeAreaConstants.safeTop, px2vp(top.height)) //在应用中存储底部安全高度 const bottom = win.getWindowAvoidArea(window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR).bottomRect AppStorage.setOrCreate<number>(SafeAreaConstants.safeBottom, px2vp(bottom.height))主要用到的API
1.窗口
windowStage 窗口管理器,管理各个基本窗口单元。
属性:getMainWindow获取这个对象下的主窗口,异步回调函数。
- 在主窗口下引用属性setWindowLayoutFullScreen 主窗口或者子窗口是否为沉浸式布局,使用promise异步回调。参数类型是布尔型 true表示沉浸式布局,false表示非沉浸式布局。
- getWindowAvoidArea 当前窗口要规避的区域

封装方法
通用工具代码/ FullScreen
import { window } from '@kit.ArkUI'
// context 是应用上下文,应用提供的一些功能对象
// 1. 组件中 getContext(this) 获取, this 组件实例, 如果是在非组件调用获取的是 undefined
// 2. 在 Ability 中,this.context 可以获取上下文
class FullScreen {
// 开启全屏
async enable () {
const ctx = AppStorage.get<Context>('context')
if (ctx) {
const win = await window.getLastWindow(ctx)
// true 开启沉浸式
win.setWindowLayoutFullScreen(true)
}
}
// 关闭全屏
async disable () {
const ctx = AppStorage.get<Context>('context')
if (ctx) {
const win = await window.getLastWindow(ctx)
// false 关闭沉浸式
win.setWindowLayoutFullScreen(false)
}
}
}
export const fullScreen = new FullScreen()
注意:获取上下文应用
1.在组件内获取上下文应用
直接
const ctx = getContext(this)
2.非组件内获取上下文应用
const ctx = AppStorage.get<Context>('context')
import { fullScreen } from '../commons/utils/FullScreen';
//应用程序主入口中
export default class EntryAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
logger.info('Ability onCreate');
// 共享给应用所有位置使用context
AppStorage.setOrCreate('context', this.context)
}
onWindowStageCreate(windowStage: window.WindowStage): void {
// Main window is created, set main page for this ability
logger.info('Ability onWindowStageCreate');
//开启沉浸式
fullScreen.enable()
windowStage.loadContent('pages/Index', (err) => {
if (err.code) {
logger.error('Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
return;
}
logger.info('Succeeded in loading the content.');
});
}
更多推荐

所有评论(0)