HarmonyOS:实现状态栏背景颜色沉浸

一、效果图

状态栏背景颜色没有改

实现状态栏背景颜色沉浸

二、实现方式

2.1 手动设置状态栏的颜色:

实现步骤:

  1. 获取并缓存窗口对象
  2. 在打开目标页面时,使用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])
  }
}
相关推荐
程序员潘Sir21 小时前
鸿蒙应用开发从入门到实战(六):ArkTS声明式UI和组件化
harmonyos·鸿蒙
猫林老师1 天前
HarmonyOS数据持久化:Preferences轻量级存储实战
华为·harmonyos
Devil枫1 天前
鸿蒙深链落地实战:从安全解析到异常兜底的全链路设计
安全·华为·harmonyos
低调小一1 天前
Android传统开发 vs Android Compose vs HarmonyOS ArkUI 对照表
android·华为·harmonyos
程序员江同学2 天前
ovCompose + AI 开发跨三端的 Now in Kotlin App
android·kotlin·harmonyos
猛码Memmat2 天前
华为HarmonyOS开发文档
华为·harmonyos
祥睿夫子2 天前
ArkTS 未被深挖的核心点:静态多态限制、静态成员与单例实战
harmonyos
高心星2 天前
HarmonyOS 5.0应用开发——V2装饰器@local的使用
harmonyos