在鸿蒙原生开发中,为了实现沉浸式效果,通常在页面中通过设置expandSafeArea属性向顶部和底部扩展安全区实现沉浸式效果,.expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM]);设置完成后,发现没有实现想要的效果,就需要点击ArkUI Inspector查看当前展示试图层级中,哪些试图没有实现沉浸式,在到代码中添加expandSafeArea属性
这种实现方式仅限于整个应用中个别页面需要沉浸式效果,其他大部分页面都要展示安全区。
如果整个应用大部分页面都需要沉浸式效果,就可以在entryAbility中统一设置窗口全屏展示,这个时候我们需要声明一个宽高的对象类来存储在AppStorageV2中,然后调用AppStorageV2的connect方法直接储存,并将生成的对象全局化,这样在对对象的属性进行修改时,就可以通过到AppStorageV2中了private deviceRect: GRDeviceInfo = AppStorageV2.connect(GRDeviceInfo , () => new GRDeviceInfo ())!;
下面是具体代码示例:
import { AppStorageV2, window } from '@kit.ArkUI';
import { GRDeviceInfo } from '../utils/GRDeviceInfo';
export class GRDeviceInfo {
topRectHeight: number = 0;
bottomRectHeight: number = 0;
}
private deviceRect: GRDeviceInfo = AppStorageV2.connect(GRDeviceInfo, () => new GRDeviceInfo())!;
let windowClass: window.Window = windowStage.getMainWindowSync();
let isLayoutFullScreen = true;
windowClass.setWindowLayoutFullScreen(isLayoutFullScreen).then(() => {
console.info('Succeeded in setting the window layout to full-screen mode.');
windowStage.loadContent('pages/Index', (err) => {
// windowStage.loadContent('pages/welcome/DDWelcomePage', (err) => {
if (err.code) {
console.error(TAG, 'Failed to load the content. Cause: %{public}s', JSON.stringify(err));
return;
}
console.info(TAG, 'Succeeded in loading the content.');
});
}).catch((err: BusinessError) => {
console.info(TAG,'Failed to set the window layout to full-screen mode. Cause:' + JSON.stringify(err));
});
//获取导航栏高度
this.deviceRect.bottomRectHeight = windowClass
.getWindowAvoidArea(window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR)
.bottomRect
.height;
// 获取状态栏区域高度
this.deviceRect.topRectHeight = windowClass
.getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM)
.topRect
.height;
// 注册监听函数,动态获取避让区域数据
windowClass.on('avoidAreaChange', (data) => {
if (data.type === window.AvoidAreaType.TYPE_SYSTEM) {
this.deviceRect.topRectHeight = data.area.topRect.height;
} else if (data.type == window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR) {
this.deviceRect.bottomRectHeight = data.area.bottomRect.height;
}
});
----------------- end ---------------
后面会继续补充不足之处。