一、效果图
状态栏背景颜色没有改
实现状态栏背景颜色沉浸
二、实现方式
2.1 手动设置状态栏的颜色:
实现步骤:
- 获取并缓存窗口对象
- 在打开目标页面时,使用setWindowSystemBarProperties接口设置状态栏属性
获取并缓存窗口对象
2.2 对顶部组件使用expandSafeArea属性扩展安全区域属性,实现状态栏沉浸
效果图
示例代码
c
@Entry
@Component
struct TestFullBg {
@State message: string = '实现状态栏背景颜色沉浸';
build() {
RelativeContainer() {
Text(this.message)
.id('TestFullBgHelloWorld')
.fontSize(30)
.fontWeight(FontWeight.Medium)
.alignRules({
center: { anchor: '__container__', align: VerticalAlign.Center },
middle: { anchor: '__container__', align: HorizontalAlign.Center }
})
}
.height('100%')
.width('100%')
.backgroundColor(Color.Pink)
// 设置顶部绘制延伸到状态栏
.expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP])
}
}
2.3 设置窗口的背景色来实现沉浸式效果
效果图
示例代码
c
// EntryAbility.ets
onWindowStageCreate(windowStage: window.WindowStage): void {
windowStage.loadContent('pages/Example', (err, data) => {
if (err.code) {
return;
}
// 设置全窗颜色和应用元素颜色一致
windowStage.getMainWindowSync().setWindowBackgroundColor('#ff9f96f8');
});
}
TestFullBg.ets文件代码
c
@Entry
@Component
struct TestFullBg {
@State message: string = '实现状态栏背景颜色沉浸';
build() {
RelativeContainer() {
Text(this.message)
.id('TestFullBgHelloWorld')
.fontSize(30)
.fontWeight(FontWeight.Medium)
.alignRules({
center: { anchor: '__container__', align: VerticalAlign.Center },
middle: { anchor: '__container__', align: HorizontalAlign.Center }
})
}
.height('100%')
.width('100%')
// .backgroundColor(Color.Pink)
.backgroundColor('ff9f96f8')
// 设置顶部绘制延伸到状态栏
// .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP])
}
}