鸿蒙开发——自定义主题色

1、概述

ArkTs提供了应用内主题切换功能,支持全局主题切换,也支持局部主题切换,效果如下。本文针对主题切换做简单介绍

2、主题色

ArkTs提供了一套内置主题配色,有Colors对象持有,它包含了默认情况下,关于主题的基本资源枚举,枚举的key与说明如下:

brand  品牌色。
warning  一级警示色。
alert  二级提示色。
confirm  确认色。
fontPrimary  一级文本字体颜色。
fontSecondary  二级文本字体颜色。
fontTertiary  三级文本字体颜色。
fontFourth  四级文本字体颜色。
fontEmphasize  高亮字体颜色。
fontOnPrimary  一级文本反转颜色,用于彩色背景。
fontOnSecondary  二级文本反转颜色,用于彩色背景。
fontOnTertiary  三级文本反转颜色,用于彩色背景。
fontOnFourth  四级文本反转颜色,用于彩色背景。
iconPrimary  一级图标颜色。
iconSecondary  二级图标颜色。
iconTertiary  三级图标颜色。
iconFourth  四级图标颜色。
iconEmphasize  高亮图标颜色。
iconSubEmphasize  高亮辅助图标颜色。
iconOnPrimary  一级图标反转颜色,用于彩色背景。
iconOnSecondary  二级图标反转颜色,用于彩色背景。
iconOnTertiary  三级图标反转颜色,用于彩色背景。
iconOnFourth  四级图标反转颜色,用于彩色背景。
backgroundPrimary  一级背景颜色(实色,不透明)。
backgroundSecondary  二级背景颜色(实色,不透明)。
backgroundTertiary  三级背景颜色(实色,不透明)。
backgroundFourth  四级背景颜色(实色,不透明)。
backgroundEmphasize  高亮背景颜色(实色,不透明)。
compForegroundPrimary  前背景。
compBackgroundPrimary  白色背景。
compBackgroundPrimaryTran  白色透明背景。
compBackgroundPrimaryContrary  常亮背景。
compBackgroundGray  灰色背景。
compBackgroundSecondary  二级背景。
compBackgroundTertiary  三级背景。
compBackgroundEmphasize  高亮背景。
compBackgroundNeutral  黑色中性高亮背景颜色。
compEmphasizeSecondary  20%高亮背景颜色。
compEmphasizeTertiary  10%高亮背景颜色。
compDivider  通用分割线颜色。
compCommonContrary  通用反转颜色。
compBackgroundFocus  获焦态背景颜色。
compFocusedPrimary  获焦态一级反转颜色。
compFocusedSecondary  获焦态二级反转颜色。
compFocusedTertiary  获焦态三级反转颜色。
interactiveHover  通用悬停交互式颜色。
interactivePressed  通用按压交互式颜色。
interactiveFocus  通用获焦交互式颜色。
interactiveActive  通用激活交互式颜色。
interactiveSelect  通用选择交互式颜色。
interactiveClick  通用点击交互式颜色。

 对应的颜色罗列如下:

我们可以在默认值的基础上对指定的颜色值做复写,其余部分将会使用默认值。假设我们需要修改几个颜色:brand、fontPrimary、iconOnPrimary、iconFourth,修改方法示意如下:

 // AppTheme.ets
import { CustomColors, CustomTheme } from '@kit.ArkUI'
export class AppColors implements CustomColors {
  //自定义主题色
  brand = 0xFF75D9;
  fontPrimary = 0xFFD53032
  iconOnPrimary = 0xFFD53032
  iconFourth = 0xFFD53032
}
export class AppTheme implements CustomTheme {
  public colors: AppColors = new AppColors()
}
export let gAppTheme: CustomTheme = new AppTheme()

2.1、设置自定义全局主题

我们可以在UIAbility中设置ThemeControl,在onWindowStageCreate()方法中setDefaultTheme,设置应用内组件的自定义主题色。

代码如下(26行):​​

// EntryAbility.ets
import {AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { window, CustomColors, ThemeControl } from '@kit.ArkUI';
import { gAppTheme } from './AppTheme'
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(gAppTheme)
      hilog.info(0x0000, 'testTag', '%{public}s', 'ThemeControl.setDefaultTheme done');
    });
  }
}

设置好后,我们写一个Page,代码如下:

@Entry
@Component
struct DisplayPage {
  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')
        }
        ListItem() {
          Column() {
            Text('Brightness')
              .width('100%')
              .margin({ top: '5vp', left: '14fp' })
            Slider({ value: 40, max: 100 })
          }
          .width('100%')
          .height('70vp')
          .borderRadius('10vp')
        }
        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')
        }
      }
    }
    .padding('10vp')
    .backgroundColor('#dcdcdc')
    .width('100%')
    .height('100%')
  }
}

效果如下(注意,在预览器里面看到的效果是默认主题效果,需要真机或模拟器才可以看到真实效果):

默认情况下,效果如下: 

2.3、Page中获取自定义主题

我们可以在onWillApplyTheme回调函数获取用于使自定义组件获取当前生效的Theme对象。我们可以获取自定义的主题对象,读取指定的主题色值,代码示例如下(9 ~ 10行):​​​​​​

import { Theme, ThemeControl } from '@kit.ArkUI'
  @Entry
  @Component
  struct DisplayPage {
    @State menuItemColor: ResourceColor = $r('sys.color.background_primary')
    
    onWillApplyTheme(theme: Theme) {
      // theme是当前生效的主题对象
      this.menuItemColor = theme.colors.backgroundPrimary;
    }
  
    build() {
    // ...
    }
  }

2.4、局部应用主题色

我们可以通过设置WithTheme,将自定义主题Theme的配色应用于内部组件的默认样式。在WithTheme的作用范围内,组件的配色会根据Theme的配色进行调整。代码如下(29行):

import { CustomColors, CustomTheme, Theme } from '@kit.ArkUI'
class AppColors implements CustomColors {
  fontPrimary: Color = Color.Pink;
  backgroundEmphasize: Color = Color.Pink;
}
class AppColorsSec implements CustomColors {
  fontPrimary: Color = Color.Orange;
  backgroundEmphasize: Color = Color.Orange;
}
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('切换主题').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({ theme: this.myTheme })可将作用域内组件的配色设置为自定义主题风格。后续可以通过更新this.myTheme来更换主题风格。onWillApplyTheme回调函数用于使自定义组件能够获取当前生效的Theme对象。效果如下:

### 鸿蒙应用开发中的自定义系统参数 在鸿蒙操作系统中,开发者可以通过配置文件来设置应用程序的行为和外观。对于自定义系统参数而言,通常涉及修改或扩展默认的应用程序行为。 #### 使用`config.json` 为了实现自定义系统参数,在项目根目录下的`config.json`文件中可以指定一些全局性的属性。这些属性能够影响整个应用的表现形式以及功能特性[^1]。 ```json { "app": { "bundleName": "com.example.myapp", "version": { "code": 1, "name": "1.0" } }, "deviceConfig": [ { "screenDensity": ["hdpi", "xhdpi"], "minApiVersion": 7 } ] } ``` 此JSON结构允许设定诸如屏幕密度支持范围(`screenDensity`)或者最低API版本号(`minApiVersion`)等重要参数。 #### 定义环境变量 除了通过静态配置外,还可以利用环境变量机制动态调整某些运行期选项。这特别适用于那些希望保持灵活性而不必重新编译代码的情况。例如: - `HARMONY_HOME`: 指向Harmony OS SDK安装路径。 - `DEBUG_MODE`: 控制调试模式开关状态。 上述方法提供了两种途径来自定义鸿蒙系统的特定方面;然而需要注意的是,并不是所有的系统级设置都可以被轻易更改——部分核心服务可能受到严格保护而无法直接操作。 #### 创建并注册新的能力(Capability) 当涉及到更深层次的功能定制时,则需考虑创建一个新的Ability(即能力)。这种做法不仅限于界面元素的设计,还包括后台逻辑处理等方面。一旦完成新能力的编码工作之后,还需要将其正式加入到项目的清单文件里以便正确加载与初始化[^2]。 ```xml <abilities> <ability name="MainAbility"> <!-- Other configurations --> </ability> </abilities> ``` 以上措施共同构成了一个较为完整的解决方案框架,使得开发者能够在遵循安全性和稳定性原则的前提下有效地实施个性化的系统参数调整方案。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值