
一、在EntryAbility的onCreate()函数中添加下面代码:
AppStorage.setOrCreate<ConfigurationConstant.ColorMode>('currentColorMode', this.context.config.colorMode);
二、在EntryAbility中添加函数
onConfigurationUpdate(newConfig: Configuration): void {const currentColorMode: ConfigurationConstant.ColorMode | undefined = AppStorage.get('currentColorMode');if (currentColorMode !== newConfig.colorMode) {AppStorage.setOrCreate<ConfigurationConstant.ColorMode>('currentColorMode', newConfig.colorMode);}}
添加上面函数后,需要引入import { Configuration } from '@kit.AbilityKit';否则会报错。
三、在需要的页面添加下面代码:
@StorageProp('currentColorMode') @Watch('onCurrentColorModeChange') currentColorMode: ConfigurationConstant.ColorMode =ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET;private isSystemDark: boolean = false;
四、添加函数
onCurrentColorModeChange(): void {if (this.currentColorMode === ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT) {this.isSystemDark = false;} else if (this.currentColorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK) {this.isSystemDark = true;}}
五、解释
isSystemDark 是我定义的变量。