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])
  }
}
相关推荐
心态还需努力呀6 小时前
把 Flameshot 编译进鸿蒙 PC:一次 Qt C++ 截图工具的源码级移植实战
c++·qt·harmonyos
心态还需努力呀6 小时前
把 Zettlr 搬上鸿蒙 PC:一次 Electron 应用移植实战
华为·electron·harmonyos
OH_TPC6 小时前
HarmonyOS APP开发---“心动卡“社交匹配App,需要用到这个库
华为·harmonyos·鸿蒙
●VON7 小时前
Flutter 鸿蒙插件适配实战:用 is_lock_screen 2.0.0 判断真实锁屏状态
flutter·华为·harmonyos
Sunny_G7 小时前
鸿蒙 Markdown 编辑器表格所见即所得:七个版本的渲染重构(CodeMirror Decoration 实战)
ai编程·harmonyos
●VON8 小时前
Flutter 鸿蒙插件适配实战:用 flutter_timezone_observer 1.2.0 监听系统时区变化
flutter·华为·harmonyos
●VON8 小时前
Flutter 鸿蒙 app_install_date 0.1.5 使用实战:读取应用安装时间
flutter·华为·harmonyos
Dream-Y.ocean9 小时前
鸿蒙平台 Apache Tomcat 管理控制台适配实战:基于 Electron 壳方案的真实 HTTP 服务器实现
tomcat·apache·harmonyos
●VON10 小时前
Flutter 鸿蒙插件适配实战:flutter_screenshot_detect 0.1.7 截图事件监听
flutter·华为·harmonyos·鸿蒙