[ArkUI开发技巧] 应用的全屏式沉浸适配
引言 在开发应用的过程中,为了使用户聚焦在应用本身,最好对应用进行沉浸适配。先前有一种适配方法,将SystemBarProperties设置成应用页面顶部和底部的颜色,但是这种方法在切换页面的过程中过渡十分僵硬,且应用在小窗模式下切换页面会强制全屏,因此不太尽如人意。本文将介绍一种优化过的方法,实现应
引言
在开发应用的过程中,为了使用户聚焦在应用本身,最好对应用进行沉浸适配。先前有一种适配方法,将SystemBarProperties设置成应用页面顶部和底部的颜色,但是这种方法在切换页面的过程中过渡十分僵硬,且应用在小窗模式下切换页面会强制全屏,因此不太尽如人意。本文将介绍一种优化过的方法,实现应用的沉浸适配。
原理
通过将应用样式设置为全屏,将SystemBarProperties背景设置为透明,contentColor随页面变化实现沉浸效果
代码实现
-
页面的代码调整
为实现沉浸后,应用内容不入侵状态栏,需要给状态栏预留空间。因此,需要将页面最外层且设置了颜色的容器组件的padding.top设置为原有值+36(具体值随不同设备类型可能有变化,但36为phone形态设备的建议值)
@Entry
@Component
struct Page {
build() {
Column() {
Text("Hello World!")
}
.padding({top: 36})
.backgroundColor(Color.White)
}
}
额外建议
考虑到用户不一定使用手势导航,底部TabBar最好也预留空间
-
Utils的编写
为了简化代码,提高复用率,我们应该编写一个沉浸Utils类来控制,代码如下:
// This file is part of libNMC, which is the foundation of ohos-weather.
// Copyright (C) 2023 Tingjin<dev@peercat.cn>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
import window from '@ohos.window';
export class ImmersiveUtils {
public static immersive(windowStage: window.WindowStage, config: {
barColor: string,
contentColor: string,
navigationColor: string,
navigatorColor: string
}) {
windowStage.getMainWindow()
.then(win => {
win.setWindowSystemBarProperties({
statusBarColor: config.barColor,
statusBarContentColor: config.contentColor,
navigationBarColor: config.navigationColor,
navigationBarContentColor: config.navigatorColor
});
})
}
}
代码来自于我的开源项目ohos-weather
config
包含了SystemBarProperties属性信息,用本方法时,一般将barColor和navigationColor设置为#00ffffff,即透明,根据应用背景色来调整contentColor和navigatorColor
-
EntryAbility的修改
在EntryAbility的onWindowStageCreate回调中,我们需要添加
globalThis.windowStage = windowStage;
windowStage.getMainWindow()
.then(win => {
win.setWindowLayoutFullScreen(true);
})
-
实现沉浸
最后即可实现沉浸,在页面onPageShow生命周期回调中,使用如下代码实现沉浸
ImmersiveUtils.immersive(globalThis.windowStage, StyleConstant.IMMERSIVE_CONFIG.INDEX);
其中第二个参数应根据你应用的实际情况进行修改,在ohos-weather中,StyleConstant.IMMERSIVE_CONFIG.INDEX的内容如下
INDEX: {
barColor: "#00286098",
contentColor: "#ffffff",
navigationColor: "#005d99d6",
navigatorColor: "#ffffff"
}
更多推荐
所有评论(0)