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])
  }
}
相关推荐
chenyingjian1 天前
鸿蒙|性能优化-概述与工具使用
harmonyos
二流小码农1 天前
鸿蒙开发:路由组件升级,支持页面一键创建
android·ios·harmonyos
TT_Close2 天前
【Flutter×鸿蒙】debug 包也要签名,这点和 Android 差远了
android·flutter·harmonyos
TT_Close2 天前
【Flutter×鸿蒙】FVM 不认鸿蒙 SDK?4步手动塞进去
flutter·swift·harmonyos
hqk2 天前
鸿蒙项目实战:手把手带你实现 WanAndroid 布局与交互
android·前端·harmonyos
TT_Close2 天前
【Flutter×鸿蒙】一个"插队"技巧,解决90%的 command not found
flutter·harmonyos
Hcourage4 天前
鸿蒙工程获取C/C++代码覆盖
harmonyos
二流小码农4 天前
鸿蒙开发:上传一张参考图片便可实现页面功能
android·ios·harmonyos
万少4 天前
HarmonyOS 开发必会 5 种 Builder 详解
前端·harmonyos
Huang兄5 天前
鸿蒙-List和Grid拖拽排序:仿微信小程序删除效果
harmonyos·arkts·arkui