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])
  }
}
相关推荐
智塑未来18 小时前
鸿蒙游戏体验手册:四种能力从性能到玩法逐一解锁
游戏·华为·harmonyos
math_hongfan19 小时前
鸿蒙离线数据缓存高级架构:弱网预加载/离线数据优先级/同步冲突解决/上线后数据合并策略
学习·缓存·华为·架构·harmonyos·鸿蒙
math_hongfan1 天前
鸿蒙企业级数据存储高级架构:从读写分离到冷热数据分层/归档策略/数据生命周期管理最佳实践
人工智能·学习·华为·架构·harmonyos·鸿蒙
math_hongfan1 天前
鸿蒙存储异常高级排查:文件损坏检测/数据恢复/读写失败重试/磁盘空间预警系统性根治方案
学习·华为·harmonyos·鸿蒙
lilian2331 天前
Harmony os 技术实战|拼豆制图10:把取消、解析失败和保存失败写成可恢复状态机
java·javascript·华为·harmonyos
2501_919749031 天前
华为鸿蒙美缝剂实用APP—小羊美缝
华为·harmonyos
2501_919749031 天前
华为鸿蒙积攒年度高光APP—小羊高光
华为·harmonyos
智塑未来1 天前
鸿蒙7碰一碰智感交互——碰哪儿传哪儿
华为·harmonyos
math_hongfan1 天前
鸿蒙存储碎片高级清理机制:数据库Vacuum/文件碎片整理/缓存过期清理/主动空间回收策略
jvm·数据库·学习·缓存·华为·harmonyos·鸿蒙
梦想不只是梦与想1 天前
鸿蒙UI测试框架:UITest
harmonyos·uitest·ui测试框架