如何适配鸿蒙的深色模式?
·
本文章使用 preferences(首选项)实现app的模式记忆和统一的util类来调用相关方法
首先编写白天黑夜切换的util类
import { common, ConfigurationConstant } from '@kit.AbilityKit'
import { preferences } from '@kit.ArkData'
// 编写黑夜切换类
export class ColorMode{
// 需要传入ApplicationContext来控制白天黑夜模式
private context:common.ApplicationContext
// 引入首选项用来保存白天黑夜的状态
private preferenceInstance:preferences.Preferences|null = null;
constructor(context:common.ApplicationContext) {
this.context = context
this.initPreference()
}
// 更新颜色模式的方法
setColorMode(mode:string){
// 黑夜
if(mode == 'dark'){
this.context.setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_DARK)
this.putMode(mode)
}
// 白天
if(mode == 'light'){
this.context.setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT)
this.putMode(mode)
}
// 默认(跟随系统)
if(mode == 'default'){
this.context.setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET)
this.putMode(mode)
}
}
// 初始化首选项
initPreference(){
let option:preferences.Options = {
name:'colorMode'
}
this.preferenceInstance = preferences.getPreferencesSync(this.context,option)
}
// 更改模式写入首选项
putMode(mode:string){
this.preferenceInstance?.putSync('mode',mode)
this.preferenceInstance?.flush()
}
// 获取当前模式用于在entryability进行进入的初始化
getMode():string{
return this.preferenceInstance!.getSync("mode","default") as string
}
}
编写在entryability调用的切换黑夜白天模式的方法
// 编写在entryability调用的切换黑夜白天模式的方法
export function ChangeEntryAbilityColor(context:common.ApplicationContext){
let colorMode = new ColorMode(context)
const mode = colorMode.getMode()
colorMode.setColorMode(mode)
}
实际案例
在entryablity中加入方法
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
// this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET);
hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onCreate');
...
ChangeEntryAbilityColor(this.context.getApplicationContext())
}
更改模式(如app的设置中)
this.ColorModeInstance?.setColorMode('light')
this.ColorModeInstance 为上面的ColorMode的一个实例化对象直接调用setColorMode即可
更多推荐
所有评论(0)