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

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

HarmonyOS
2024-05-22 23:29:59
1033浏览
收藏 0
回答 1
回答 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%') 
  } 
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.

总结:

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

实现效果

注明适配的版本信息

IDE:DevEco    Studio 4.1.3.500

SDK:HarmoneyOS    4.0.10.16

分享
微博
QQ
微信
回复
2024-05-23 21:17:52


相关问题
HarmonyOS 如何监听深浅色模式
675浏览 • 1回复 待解决
HarmonyOS 主动设置深浅色模式
848浏览 • 1回复 待解决
app适配深色浅色切换模式
2625浏览 • 1回复 待解决
HarmonyOS 浅色模式与深色模式
899浏览 • 1回复 待解决
应用如何切换夜间模式
2140浏览 • 1回复 待解决