# 【鸿蒙开发】如何设置系统模式(深色模式/浅色模式)

【鸿蒙开发】如何设置系统模式(深色模式/浅色模式)

前言

本文主要介绍了怎么设置应用的系统模式,包括深色模式、浅色模式、跟随系统,以及如何持久化存储用户选择的模式,以如何封装该工具类举例。

封装切换系统模式的工具类

首先可以在华为的官网上了解ApplicationContext.setColorMode设置应用的颜色模式的API
在这里插入图片描述
ColorMode的类型
在这里插入图片描述

1.初始持久化系统颜色模式

初始化的时候,我们设置当前模式为跟随系统,当用户设置模式之后,我们需要将用户设置的模式做一个持久化操作,这样用户下次使用时能保持之前的偏好。

  //启动页调用初始化使用
  init() {
    // 需求:持久化设置深色普通模式
    // 1、PersistStroage持久化存储颜色模式
    PersistentStorage.persistProp(ColorModeKey, ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET)
    // 2、在设置中,点击修改颜色模式时,要将颜色模式存储到AppStroage中
    const colorMode = AppStorage.get<ConfigurationConstant.ColorMode>(ColorModeKey)
    //在应用入口存储当前上下文,通过get方法拿到当前上下文
    const ctx = AppStorage.get<Context>('context')
    //或者getContext()方法来获取到上下文
    const ctx = getContext()
    // 4、启动App时 要把颜色模式设置为持久化存储的颜色模式
    ctx?.getApplicationContext().setColorMode(colorMode)
  }

2.封装设置颜色方法

  setTheme(mode: ConfigurationConstant.ColorMode) {
    const ctx = AppStorage.get<Context>('context')
    ctx?.getApplicationContext().setColorMode(mode)
    AppStorage.set(ColorModeKey, mode)
  }

3.设置颜色模式

可以将工具类导出实例,这样在需要用的地方直接调用即可

  //设置浅色模式
  setLight() {
    this.setTheme(ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT)
  }

  //设置深色模式
  setDark() {
    this.setTheme(ConfigurationConstant.ColorMode.COLOR_MODE_DARK)
  }

  //设置跟随系统
  setNot() {
    this.setTheme(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET)
  }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值