深色模式现在已经成为很多APP的标配,因此我们在开发鸿蒙版本的APP时也适配了深色模式,具体适配方法如下
1:创建深色模式目录
打开要创建深色模式的模块,选择该模块下的resources目录,右击选择 new -> resources directory ,会出现如下图,选择 color mode ,并点击向右的箭头,选择color mode中的dark后点击ok ,即创建了深色模式的dark目录,在drak目录下的element目录下放入color.json文件,这里的color.json文件中存放的就是深色模式下的色值库
image.png
image.png
image.png
2:设置深色模式的方法
//跟随系统
getContext(this)
.getApplicationContext()
.setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET)
//深色模式
getContext(this)
.getApplicationContext()
.setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_DARK)
//浅色模式
getContext(this)
.getApplicationContext()
.setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT)
3:设置完深色模式之后,需要存储一个变量到存储卡中以永久保存,方法如下:
//声明变量
@StorageLink('colorMode') private colorMode: number = ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT
//设置深色模式后直接对变量进行赋值,示例如下:
this.colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET
4:在APP的启动页(SplashPage)读取我们保存的变量,对APP的模式进行设置:
//这里建议默认设置为跟随系统
PersistentStorage.persistProp('colorMode', ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET);
let colorMode = AppStorage.get<ConfigurationConstant.ColorMode>('colorMode')
if (colorMode == ConfigurationConstant.ColorMode.COLOR_MODE_DARK) {
getContext(this).getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_DARK);
} else if (colorMode == ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET) {
getContext(this).getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET);
} else {
getContext(this).getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT);
}