鸿蒙:更改状态栏、导航栏颜色

前言:

最近在学习深色模式切换的时候,注意到状态栏颜色是可以自行设置的,在这里,我做下分享。

官方文档参考下方:

https://developer.huawei.com/consumer/cn/doc/architecture-guides/architecture-v1-3_2-ts_45-0000002378096446https://developer.huawei.com/consumer/cn/doc/architecture-guides/architecture-v1-3_2-ts_45-0000002378096446

【这里给大家提供两种方案】

方案一:

逻辑写在组件内部,运行效果和代码如下:

Index.ets

复制代码
import window from '@ohos.window';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct Index {

changeColor(){
  let windowClass: window.Window | undefined = undefined;
  window.getLastWindow(getContext(), (err: BusinessError, data) => {
    windowClass = data
    let SystemBarProperties: window.SystemBarProperties = {
      statusBarColor: '#2b2b2b',
      statusBarContentColor: '#fc5531'
    };
    try {
      let promise = windowClass.setWindowSystemBarProperties(SystemBarProperties);
      promise.then(() => {
        console.info('Succeeded in setting the system bar properties.');
      }).catch((err: BusinessError) => {
        console.error(`Failed to set the system bar properties. Cause code: ${err.code}, message: ${err.message}`);
      });
    } catch (exception) {
      console.error(`Failed to set the system bar properties. Cause code: ${exception.code}, message: ${exception.message}`);
    }
  })
}

  build() {
   Column(){
     Button("变更颜色")
       .onClick(()=>{
         this.changeColor()
       })
    }
    .justifyContent(FlexAlign.Center)
    .height('100%')
    .width('100%')
  }
}

方案二:

逻辑抽离到一个工具类中,运行效果如下:

代码如下:

StatusBarManager.ets

复制代码
import { common } from "@kit.AbilityKit";
import { window } from "@kit.ArkUI";
import { BusinessError } from "@kit.BasicServicesKit";

export class StatusBarManager {
  static handleStatusBarAction(context: common.BaseContext, p: string): void {
    try {
      interface ParamsType {
        action: string;
        args: Array<string>;
      }

      const params: ParamsType = JSON.parse(p);
      const action: string = params.action;
      const args: Array<string> = params.args;

      let statusBarColor = '#007dff';

      if (action === 'backgroundColorByHexString') {
        statusBarColor = args[0] || statusBarColor;
      }

      const systemBarProperties: window.SystemBarProperties = {
        statusBarColor: statusBarColor,
        statusBarContentColor: '#F7CE00',
      };

      StatusBarManager.setStatusBarBgColor(context, systemBarProperties);
    } catch (error) {
      console.error('Failed to parse or handle status bar action. Error:');
    }
  }

  private static setStatusBarBgColor(context: common.BaseContext,
    systemBarProperties: window.SystemBarProperties): void {
    window.getLastWindow(context).then((windowClass: window.Window) => {
      try {
        windowClass.setWindowSystemBarProperties(systemBarProperties);
        console.info('Status bar color updated successfully.');
      } catch (exception) {
        console.error('Failed to set the system bar properties. Cause: ');
      }
    }).catch((error: BusinessError) => {
      console.error('Failed to get last window. Error: ');
    });
  }
}

Index.ets

复制代码
import window from '@ohos.window';
import { BusinessError } from '@kit.BasicServicesKit';
import { StatusBarManager } from './StatusBarManager';
import { common } from '@kit.AbilityKit';

@Entry
@Component
struct Index {

changeColor(){
  let windowClass: window.Window | undefined = undefined;
  window.getLastWindow(getContext(), (err: BusinessError, data) => {
    windowClass = data
    let SystemBarProperties: window.SystemBarProperties = {
      statusBarColor: '#2b2b2b',
      statusBarContentColor: '#fc5531'
    };
    try {
      let promise = windowClass.setWindowSystemBarProperties(SystemBarProperties);
      promise.then(() => {
        console.info('Succeeded in setting the system bar properties.');
      }).catch((err: BusinessError) => {
        console.error(`Failed to set the system bar properties. Cause code: ${err.code}, message: ${err.message}`);
      });
    } catch (exception) {
      console.error(`Failed to set the system bar properties. Cause code: ${exception.code}, message: ${exception.message}`);
    }
  })
}

  build() {
   Column(){
     Button("变更颜色")
       .onClick(()=>{
         StatusBarManager.handleStatusBarAction(this.getUIContext().getHostContext() as common.UIAbilityContext, '{}')

       })
    }
    .justifyContent(FlexAlign.Center)
    .height('100%')
    .width('100%')
  }
}
相关推荐
不爱吃糖的程序媛1 小时前
Flutter 开发的鸿蒙AtomGit OAuth 授权应用
华为·harmonyos
xq95276 小时前
编程之路 2025年终总结 ,勇往直前 再战江湖
harmonyos
不爱吃糖的程序媛7 小时前
鸿蒙PC命令行开发 macOS 上解决 pkg-config 命令未安装的问题
macos·华为·harmonyos
二流小码农9 小时前
鸿蒙开发:自定义一个圆形动画菜单
android·ios·harmonyos
yumgpkpm9 小时前
Cloudera CDP7、CDH5、CDH6 在华为鲲鹏 ARM 麒麟KylinOS做到无缝切换平缓迁移过程
大数据·arm开发·华为·flink·spark·kafka·cloudera
不爱吃糖的程序媛9 小时前
解决鸿蒙PC命令行编译 macOS 上 cp 命令参数冲突问题
macos·harmonyos·策略模式
不爱吃糖的程序媛9 小时前
OpenHarmony PC 第三方 C/C++ 库适配完整指南
c语言·c++·harmonyos
不爱吃糖的程序媛10 小时前
OpenHarmony Linux 环境 SDK 使用说明(进阶--依赖库的解决方法)
linux·运维·harmonyos
狮子也疯狂10 小时前
【生态互联】| 鸿蒙三方库的选择与适配策略
华为·harmonyos
不爱吃糖的程序媛10 小时前
鸿蒙Lycium 交叉编译框架完全指南
华为·harmonyos