切换应用深浅色模式?

功能场景描述及使用场景

场景:切换应用的深浅色模式,且不跟随系统。本例从资源分类的角度实现。

阅读 483
1 个回答

使用的核心API

getApplicationContext(): ApplicationContext(): ApplicationContext

ApplicationContext.setColorMode(colorMode: ConfigurationConstant.ColorMode): void

核心代码解释

//resources目录结构
-resources
--base//浅色模式访问
---element
----color.json
//color.json
{
  "color": [
  {
    "name": "start_window_background",
    "value": "#FFFFFF"
  }
  ]
}

--dark//深色模式访问
---element
----color.json
//color.json
{
  "color": [
  {
    "name": "start_window_background",
    "value": "#000000"
  }
  ]
}
//Index.ets
import ConfigurationConstant from '@ohos.app.ability.ConfigurationConstant';
import hilog from '@ohos.hilog';


@Entry
@Component
struct Index {
  @State message: string = 'Hello World';

  build() {
    Row() {
      Column() {
        Text("light")  //应用设置颜色模式为LIGHT
          .fontSize(40)
          .fontWeight(FontWeight.Bold)
          .onClick(() => {hilog.info(0x0000, 'testTag', 'before setColorMode');
            let context = getContext().getApplicationContext()
            context.setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT);
            console.log('------------ appUpdateConfiguration -----------'+'DARK');
          })
          .fontColor("#ffdd1a1a")
          .backgroundColor($r("app.color.start_window_background"))


        Text("dark")  // 应用设置颜色模式为DARK
          .fontSize(40)
          .fontWeight(FontWeight.Bold)
          .onClick(() => {
            hilog.info(0x0000, 'testTag', 'before setColorMode');
            let context = getContext().getApplicationContext()
            context.setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_DARK);
            console.log('------------ appUpdateConfiguration -----------'+'DARK');
          })
          .fontColor("#ffdd1a1a")
          .backgroundColor($r("app.color.start_window_background"))
      }
      .width('100%')
    }
    .backgroundColor("#ffffff")
    .height('100%')
  }
}

总结:

  • 主要难点在于:切换深浅色模式为当前较新特性,使用时需要与资源分类联动,根据系统设置访问不同目录的资源。

实现效果

注明适配的版本信息

  • IDE:DevEco Studio 4.1.3.500
  • SDK:HarmoneyOS 4.0.10.16
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进