使用的核心APIgetApplicationContext(): ApplicationContext(): ApplicationContextApplicationContext.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.500SDK:HarmoneyOS 4.0.10.16
使用的核心API
getApplicationContext(): ApplicationContext(): ApplicationContext
ApplicationContext.setColorMode(colorMode: ConfigurationConstant.ColorMode): void
核心代码解释
总结:
实现效果
注明适配的版本信息