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

前言:

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

官方文档参考下方:

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%')
  }
}
相关推荐
yuanlaile15 分钟前
Flutter开发HarmonyOS鸿蒙App商业项目实战已出炉
flutter·华为·harmonyos
cooldream20091 小时前
【案例实战】智能出行导航助手HarmonyOS 开发全流程复盘
华为·harmonyos
CodeCaptain1 小时前
可直接落地的「Flutter 桥接鸿蒙 WebSocket」端到端实施方案
websocket·flutter·harmonyos
猫林老师1 小时前
HarmonyOS图形图像处理与OpenGL ES实战
harmonyos
白鹿第一帅1 小时前
【成长纪实】星光不负 码向未来|我的 HarmonyOS 学习之路与社区成长故事
harmonyos·白鹿第一帅·成都ug社区·csdn成都站·鸿蒙开放能力·鸿蒙学习之路·鸿蒙第一课
数字化顾问1 小时前
(122页PPT)华为初级项目管理培训(附下载方式)
华为
俩毛豆1 小时前
【页面路由导航】三步实现页面跳转的完整示例
前端·harmonyos
羑悻的小杀马特3 小时前
探秘仓颉:当函数式编程遇见面向对象王国,当协程风暴席卷并发荒原——从基础语法到实战测试联动的多维编程奇遇记
华为·harmonyos·仓颉·仓颉征文·个人感受·标准库源码·语法剖析
LucianaiB3 小时前
【案例实战】基于分布式能力的跨设备任务协同应用开发
harmonyos·鸿蒙·1024程序员节·案例实战
摘星编程16 小时前
【成长纪实】HarmonyOS Next学习地图:新手避坑指南与核心知识点拆解
学习·华为·harmonyos·鸿蒙开发