目录
应用深浅色适配
当前系统存在深浅色两种显示模式,为了给用户更好的使用体验,应用应适配深浅色模式。从应用与系统配置关联的角度来看,适配深浅色模式可以分为下面两种情况:
应用跟随系统的深浅色模式
1、颜色适配
- 自定义资源实现
-
resources目录下增加深色模式限定词目录(命名为dark)并新建color.json文件,可显示深色模式颜色资源的配置
-
图1 resources目录结构示意
-
例如,开发者可在这两个color.json中定义同名配色定义并赋予不同的色值。
-
base/element/color.json文件:
TypeScript{ "color": [ { "name": "app_title_color", "value": "#000000" } ] }
-
dark/element/color.json文件:
TypeScript
{
"color": [
{
"name": "app_title_color",
"value": "#FFFFFF"
}
]
}
-
通过系统资源实现
-
开发者可直接使用的系统预置资源,即分层参数,同一资源ID在设备类型、深浅色等不同配置下有不同的取值。通过使用系统资源,不同的开发者可以开发出具有相同视觉风格的应用,不需要自定义两份颜色资源,在深浅色模式下也会自动切换成不同的颜色值。例如,开发者可调用系统资源中的文本主要配色来定义应用内文本颜色。
TypeScript
Text('使用系统定义配色')
.fontColor($r('sys.color.ohos_id_color_text_primary'))
2、图片资源适配
-
采用资源限定词目录的方式。参照颜色适配的方法,需要将深色模式下对应的同名图片放到 dark/media 目录下,再通过$r的方式加载图片资源的key值,系统做深浅色模式切换时,会自动加载对应资源文件中的value值。
对于 SVG 格式的一些简单图标,可以使用fillColor属性配合系统资源改变图片的绘制颜色。不通过两套图片资源的方式,也可以实现深浅色模式适配。
TypeScriptImage($r('app.media.pic_svg')) .width(50) .fillColor($r('sys.color.ohos_id_color_text_primary'))
3、Web组件适配
- Web组件支持对前端页面进行深色模式配置,可参考Web组件深色模式进行相关配置。
4、"自定义节点"适配
-
自定义节点BuilderNode和ComponentContent需手动传递系统环境变化事件,触发节点的全量更新。
TypeScript// 记录创建的自定义节点对象 const builderNodeMap: Array<BuilderNode<[Params]>> = new Array(); class MyFrameCallback extends FrameCallback { onFrame() { updateColorMode(); } } function updateColorMode() { builderNodeMap.forEach((value, index) => { // 通知BuilderNode环境变量改变,触发深浅色切换 value.updateConfiguration(); }) } // ... other code ... aboutToAppear() { // ... other code ... this.getUIContext()?.postFrameCallback(new MyFrameCallback()); // ... other code ... }
5、应用监听深浅色模式切换事件
-
应用可以主动监听系统深浅色模式变化,进行其他类型的资源初始化等自定义逻辑。无论应用是否跟随系统深浅色模式变化,该监听方式均可生效。
-
a. 在 AbilityStage 的 onCreate() 生命周期中获取APP当前的颜色模式并保存到 AppStorage。
TypeScript
onCreate(): void {
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
AppStorage.setOrCreate('currentColorMode', this.context.config.colorMode);
}
-
b. 在 AbilityStage 的 onConfigurationUpdate() 生命周期中获取最新变更的颜色模式并刷新到 AppStorage。
TypeScriptonConfigurationUpdate(newConfig: Configuration): void { AppStorage.setOrCreate('currentColorMode', newConfig.colorMode); hilog.info(0x0000, 'testTag', 'the newConfig.colorMode is %{public}s', JSON.stringify(AppStorage.get('currentColorMode')) ?? ''); }
-
c. 在Page中通过 @StorageProp + @Watch 方式获取当前最新颜色并监听设备深色模式变化。
TypeScript@StorageProp('currentColorMode') @Watch('onColorModeChange') currentMode: number = ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT;
-
d. 在 aboutToAppear 初始化函数中根据当前最新颜色模式刷新状态变量。
TypeScriptaboutToAppear(): void { if (this.currentMode == ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT) { //当前为浅色模式,资源初始化逻辑 }else { //当前为深色模式,资源初始化逻辑 } }
-
e. 在 @Watch 回调函数中执行同样的适配逻辑。
TypeScriptonColorModeChange(): void { if (this.currentMode == ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT) { //当前为浅色模式,资源初始化逻辑 } else { //当前为深色模式,资源初始化逻辑 } }
应用主动设置深浅色模式
应用默认配置为跟随系统切换深浅色模式,如不希望应用跟随系统深浅色模式变化,可主动设置应用的深浅色风格。设置后,应用的深浅色模式固定,不会随系统改变。
TypeScript
onCreate(): void {
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_DARK);
}
系统默认判断规则
- 如果应用调用上述setColorMode接口主动设置了深浅色,则以接口效果优先。
- 应用没有调用setColorMode接口时:
- 如果应用工程dark目录下有深色资源,则系统组件在深色模式下会自动切换成为深色。
- 如果应用工程dark目录下没有任何深色资源,则系统组件在深色模式下仍会保持浅色体验。

如果应用全部都是由系统组件/系统颜色开发,且想要跟随系统切换深浅色模式时,请参考以下示例修改代码来保证应用体验。
TypeScript
onCreate(): void {
this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET);
}
使用建议与限制
-
建议方法
-
当应用跟随系统深色或浅色模式时,建议采用AbilityStage的监听回调或Ability的监听回调方式,主动监听系统深浅色模式变化。一旦颜色模式发生变化,应通过绑定状态变量等方法,执行特定的业务逻辑。
-
不推荐方法
-
开发者在使用资源时,未采用监听系统深浅色模式变化的方式,而是在属性设置中通过函数适配深浅色变更。例如,参考以下代码写法:
TypeScript
getResource() : string {
// 获取系统颜色模式
if (colorMode == "dark") {
return "#FF000000"
} else {
return "#FFFFFFFF"
}
// ... other code ...
build() {
// ... other code ...
Button.backgroundColor(this.getResource())
// ... other code ...
}
}
这种方式依赖于切换流程中重新执行属性设置代码,随着系统的发展和性能优化,并不能确保所有属性代码均被重新执行。因为在大部分热更新场景中,重新执行全部页面构建和属性设置代码显然是冗余的。
设置应用内主题换肤
概述
对于采用ArkTS开发的应用,提供了应用内组件的主题换肤功能,支持局部的深浅色切换及动态换肤。目前,该功能只支持设置应用内主题换肤,暂不支持在UIAbility或窗口层面进行主题设置,同时也不支持C-API和Node-API。
自定义主题色
当应用需要使用换肤功能时,应自定义主题颜色。CustomTheme用于自定义主题色的内容,其属性可选,仅需要复写需修改的部分,未修改内容将继承系统默认设置,可参考系统默认的token颜色值。请参照以下示例自定义主题色:
TypeScript
import { CustomColors, CustomTheme } from '@kit.ArkUI';
export class AppColors implements CustomColors {
//自定义主题色
brand: ResourceColor = '#FF75D9';
}
export class AppTheme implements CustomTheme {
public colors: AppColors = new AppColors();
}
export let gAppTheme: CustomTheme = new AppTheme();
设置应用内组件自定义主题色
-
可以在页面入口处统一设置应用内组件自定义主题色,但需确保在页面build前执行ThemeControl。
-
其中,onWillApplyTheme回调函数用于使自定义组件获取当前生效的Theme对象。
TypeScript
import { Theme, ThemeControl } from '@kit.ArkUI';
import { gAppTheme } from './AppTheme';
//在页面build前执行ThemeControl
ThemeControl.setDefaultTheme(gAppTheme);
@Entry
@Component
struct DisplayPage {
@State menuItemColor: ResourceColor = $r('sys.color.background_primary');
onWillApplyTheme(theme: Theme) {
this.menuItemColor = theme.colors.backgroundPrimary;
}
build() {
Column() {
List({ space: 10 }) {
ListItem() {
Column({ space: '5vp' }) {
Text('Color mode')
.margin({ top: '5vp', left: '14fp' })
.width('100%')
Row() {
Column() {
Text('Light')
.fontSize('16fp')
.textAlign(TextAlign.Start)
.alignSelf(ItemAlign.Center)
Radio({ group: 'light or dark', value: 'light' })
.checked(true)
}
.width('50%')
Column() {
Text('Dark')
.fontSize('16fp')
.textAlign(TextAlign.Start)
.alignSelf(ItemAlign.Center)
Radio({ group: 'light or dark', value: 'dark' })
}
.width('50%')
}
}
.width('100%')
.height('90vp')
.borderRadius('10vp')
.backgroundColor(this.menuItemColor)
}
ListItem() {
Column() {
Text('Brightness')
.width('100%')
.margin({ top: '5vp', left: '14fp' })
Slider({ value: 40, max: 100 })
}
.width('100%')
.height('70vp')
.borderRadius('10vp')
.backgroundColor(this.menuItemColor)
}
ListItem() {
Column() {
Row() {
Column({ space: '5vp' }) {
Text('Touch sensitivity')
.fontSize('16fp')
.textAlign(TextAlign.Start)
.width('100%')
Text('Increase the touch sensitivity of your screen' +
' for use with screen protectors')
.fontSize('12fp')
.fontColor(Color.Blue)
.textAlign(TextAlign.Start)
.width('100%')
}
.alignSelf(ItemAlign.Center)
.margin({ left: '14fp' })
.width('75%')
Toggle({ type: ToggleType.Switch, isOn: true })
.margin({ right: '14fp' })
.alignSelf(ItemAlign.Center)
}
.width('100%')
.height('80vp')
}
.width('100%')
.borderRadius('10vp')
.backgroundColor(this.menuItemColor)
}
}
}
.padding('10vp')
.backgroundColor('#dcdcdc')
.width('100%')
.height('100%')
}
}
-
在UIAbility中设置ThemeControl,需要在onWindowStageCreate()方法中setDefaultTheme,设置应用内组件的自定义主题色。
TypeScriptimport {AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; import { window, CustomColors, ThemeControl } from '@kit.ArkUI'; class AppColors implements CustomColors { fontPrimary = 0xFFD53032; iconOnPrimary = 0xFFD53032; iconFourth = 0xFFD53032; } const abilityThemeColors = new AppColors(); export default class EntryAbility extends UIAbility { onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate'); } onDestroy() { hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy'); } onWindowStageCreate(windowStage: window.WindowStage) { // Main window is created, set main page for this ability hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); windowStage.loadContent('pages/Index', (err, data) => { if (err.code) { hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); return; } hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? ''); // 在onWindowStageCreate()方法中setDefaultTheme ThemeControl.setDefaultTheme({ colors: abilityThemeColors }); hilog.info(0x0000, 'testTag', '%{public}s', 'ThemeControl.setDefaultTheme done'); }); } }
如果setDefaultTheme的参数为undefined时,默认token值对应的色值参考系统缺省token色值
setDefaultTheme需要在ArkUI初始化后即windowStage.loadContent的完成时回调中使用
设置应用局部页面自定义主题风格
通过设置WithTheme,将自定义主题Theme的配色应用于内部组件的默认样式。在WithTheme的作用范围内,组件的配色会根据Theme的配色进行调整。
如示例所示,使用WithTheme({ theme: this.myTheme })可将作用域内组件的配色设置为自定义主题风格。后续可以通过更新this.myTheme来更换主题风格。onWillApplyTheme回调函数用于使自定义组件能够获取当前生效的Theme对象。
TypeScript
import { CustomColors, CustomTheme, Theme } from '@kit.ArkUI';
class AppColors implements CustomColors {
fontPrimary: ResourceColor = $r('app.color.brand_purple');
backgroundEmphasize: ResourceColor = $r('app.color.brand_purple');
}
class AppColorsSec implements CustomColors {
fontPrimary: ResourceColor = $r('app.color.brand');
backgroundEmphasize: ResourceColor = $r('app.color.brand');
}
class AppTheme implements CustomTheme {
public colors: AppColors = new AppColors();
}
class AppThemeSec implements CustomTheme {
public colors: AppColors = new AppColorsSec();
}
@Entry
@Component
struct DisplayPage {
@State customTheme: CustomTheme = new AppTheme();
@State message: string = '设置应用局部页面自定义主题风格';
count = 0;
build() {
WithTheme({ theme: this.customTheme }) {
Row(){
Column() {
Text('WithTheme')
.fontSize(30)
.margin({bottom: 10})
Text(this.message)
.margin({bottom: 10})
Button('change theme').onClick(() => {
this.count++;
if (this.count > 1) {
this.count = 0;
}
switch (this.count) {
case 0:
this.customTheme = new AppTheme();
break;
case 1:
this.customTheme = new AppThemeSec();
break;
}
})
}
.width('100%')
}
.height('100%')
.width('100%')
}
}
}

设置应用页面局部深浅色
通过WithTheme可以设置三种颜色模式,跟随系统模式,浅色模式和深色模式。
在WithTheme的作用范围内,组件的样式资源值会根据指定的模式,读取对应的深浅色模式系统和应用资源值。这意味着,在WithTheme作用范围内,组件的配色会根据所指定的深浅模式进行调整。
如下面的示例所示,通过WithTheme({ colorMode: ThemeColorMode.DARK }),可以将作用范围内的组件设置为深色模式。
设置局部深浅色时,需要添加dark.json资源文件,深浅色模式才会生效。

dark.json数据示例:
TypeScript
{
"color": [
{
"name": "start_window_background",
"value": "#FFFFFF"
}
]
}
TypeScript
@Entry
@Component
struct DisplayPage {
@State message: string = 'Hello World';
@State colorMode: ThemeColorMode = ThemeColorMode.DARK;
build() {
WithTheme({ colorMode: this.colorMode }) {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
Button('Switch ColorMode').onClick(() => {
if (this.colorMode === ThemeColorMode.LIGHT) {
this.colorMode = ThemeColorMode.DARK;
} else if (this.colorMode === ThemeColorMode.DARK) {
this.colorMode = ThemeColorMode.LIGHT;
}
})
}
.width('100%')
}
.backgroundColor($r('sys.color.background_primary'))
.height('100%')
.expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.END, SafeAreaEdge.BOTTOM, SafeAreaEdge.START])
}
}
}

系统缺省token色值
Token | 场景类别 | Light | Dark | ||
---|---|---|---|---|---|
theme.colors.brand | 品牌色 | #ff0a59f7 | ![]() |
#ff317af7 | ![]() |
theme.colors.warning | 一级警示色 | #ffe84026 | ![]() |
#ffd94838 | ![]() |
theme.colors.alert | 二级警示色 | #ffed6f21 | ![]() |
#ffdb6b42 | ![]() |
theme.colors.confirm | 确认色 | #ff64bb5c | ![]() |
#ff5ba854 | ![]() |
theme.colors.fontPrimary | 一级文本 | #e5000000 | ![]() |
#e5ffffff | ![]() |
theme.colors.fontSecondary | 二级文本 | #99000000 | ![]() |
#99ffffff | ![]() |
theme.colors.fontTertiary | 三级文本 | #66000000 | ![]() |
#66ffffff | ![]() |
theme.colors.fontFourth | 四级文本 | #33000000 | ![]() |
#33ffffff | ![]() |
theme.colors.fontEmphasize | 高亮文本 | #ff0a59f7 | ![]() |
#ff317af7 | ![]() |
theme.colors.fontOnPrimary | 一级文本反色 | #ffffffff | ![]() |
#ff000000 | ![]() |
theme.colors.fontOnSecondary | 二级文本反色 | #99ffffff | ![]() |
#99000000 | ![]() |
theme.colors.fontOnTertiary | 三级文本反色 | #66ffffff | ![]() |
#66000000 | ![]() |
theme.colors.fontOnFourth | 四级文本反色 | #33ffffff | ![]() |
#33000000 | ![]() |
theme.colors.iconPrimary | 一级图标 | #e5000000 | ![]() |
#e5ffffff | ![]() |
theme.colors.iconSecondary | 二级图标 | #99000000 | ![]() |
#99ffffff | ![]() |
theme.colors.iconTertiary | 三级图标 | #66000000 | ![]() |
#66ffffff | ![]() |
theme.colors.iconFourth | 四级图标 | #33000000 | ![]() |
#33ffffff | ![]() |
theme.colors.iconEmphasize | 高亮图标 | #ff0a59f7 | ![]() |
#ff317af7 | ![]() |
theme.colors.iconSubEmphasize | 高亮辅助图标 | #660a59f7 | ![]() |
#66317af7 | ![]() |
theme.colors.iconOnPrimary | 一级图标反色 | #ffffffff | ![]() |
#ff000000 | ![]() |
theme.colors.iconOnSecondary | 二级图标反色 | #99ffffff | ![]() |
#99000000 | ![]() |
theme.colors.iconOnTertiary | 三级图标反色 | #66ffffff | ![]() |
#66000000 | ![]() |
theme.colors.iconOnFourth | 四级图标反色 | #33ffffff | ![]() |
#33000000 | ![]() |
theme.colors.backgroundPrimary | 一级背景(实色/不透明色) | #ffffffff | ![]() |
#ffe5e5e5 | ![]() |
theme.colors.backgroundSecondary | 二级背景(实色/不透明色) | #fff1f3f5 | ![]() |
#ff191a1c | ![]() |
theme.colors.backgroundTertiary | 三级背景(实色/不透明色) | #ffe5e5ea | ![]() |
#ff202224 | ![]() |
theme.colors.backgroundFourth | 四级背景(实色/不透明色) | #ffd1d1d6 | ![]() |
#ff2e3033 | ![]() |
theme.colors.backgroundEmphasize | 高亮背景(实色/不透明色) | #ff0a59f7 | ![]() |
#ff317af7 | ![]() |
theme.colors.compForegroundPrimary | 前背景 | #ff000000 | ![]() |
#ffe5e5e5 | ![]() |
theme.colors.compBackgroundPrimary | 白色背景 | #ffffffff | ![]() |
#ffffffff | ![]() |
theme.colors.compBackgroundPrimaryTran | 白色透明背景 | #ffffffff | ![]() |
#33ffffff | ![]() |
theme.colors.compBackgroundPrimaryContrary | 常亮背景 | #ffffffff | ![]() |
#ffe5e5e5 | ![]() |
theme.colors.compBackgroundGray | 灰色背景 | #fff1f3f5 | ![]() |
#ffe5e5ea | ![]() |
theme.colors.compBackgroundSecondary | 二级背景 | #19000000 | ![]() |
#19ffffff | ![]() |
theme.colors.compBackgroundTertiary | 三级背景 | #0c000000 | ![]() |
#0cffffff | ![]() |
theme.colors.compBackgroundEmphasize | 高亮背景 | #ff0a59f7 | ![]() |
#ff317af7 | ![]() |
theme.colors.compBackgroundNeutral | 黑色中性高亮背景 | #ff000000 | ![]() |
#ffffffff | ![]() |
theme.colors.compEmphasizeSecondary | 20%高亮背景 | #330a59f7 | ![]() |
#33317af7 | ![]() |
theme.colors.compEmphasizeTertiary | 10%高亮背景 | #190a59f7 | ![]() |
#19317af7 | ![]() |
theme.colors.compDivider | 分割线颜色 | #33000000 | ![]() |
#33ffffff | ![]() |
theme.colors.compCommonContrary | 通用反色 | #ffffffff | ![]() |
#ff000000 | ![]() |
theme.colors.compBackgroundFocus | 获焦态背景色 | #fff1f3f5 | ![]() |
#ff000000 | ![]() |
theme.colors.compFocusedPrimary | 获焦态一级反色 | #e5000000 | ![]() |
#e5ffffff | ![]() |
theme.colors.compFocusedSecondary | 获焦态二级反色 | #99000000 | ![]() |
#99ffffff | ![]() |
theme.colors.compFocusedTertiary | 获焦态三级反色 | #66000000 | ![]() |
#66ffffff | ![]() |
theme.colors.interactiveHover | 通用悬停交互式颜色 | #0c000000 | ![]() |
#0cffffff | ![]() |
theme.colors.interactivePressed | 通用按压交互式颜色 | #19000000 | ![]() |
#19ffffff | ![]() |
theme.colors.interactiveFocus | 通用获焦交互式颜色 | #ff0a59f7 | ![]() |
#ff317af7 | ![]() |
theme.colors.interactiveActive | 通用激活交互式颜色 | #ff0a59f7 | ![]() |
#ff317af7 | ![]() |
theme.colors.interactiveSelect | 通用选择交互式颜色 | #33000000 | ![]() |
#33ffffff | ![]() |
theme.colors.interactiveClick | 通用点击交互式颜色 | #19000000 | ![]() |
#19ffffff | ![]() |