目录

1. 引言

2. 系统架构设计

2.1 架构概述

2.2 核心模块关系

3. 核心代码实现

3.1 常量定义(ThemeConstants)

3.2 主题配置(ThemeConfig)

3.3 主题管理器(ThemeManager)

3.4 样式管理器(StyleManager)

4. 主题化组件开发

4.1 ThemeButton 组件

4.2 ThemeCard 组件

4.3 ThemeText 组件

5. 主题化组件使用示例

5.1 在页面中使用主题化组件

6. 最佳实践与优化建议

6.1 性能优化

6.2 可维护性提升

6.3 扩展性考虑

7. 总结


1. 引言

在 HarmonyOS 应用开发中,界面风格的统一管理是提升用户体验、降低开发维护成本的重要环节。通过我个人学习开发ArkTS代码实践,我感受很深刻。

特别是对于复杂应用,缺乏统一的主题管理会导致界面风格不一致、代码冗余、维护困难等问题。本文将详细介绍如何基于 ArkTS 构建一个灵活、高效的界面风格统一管理系统。

通过本文介绍的解决方案,开发者可以轻松实现:

  • 浅色/深色主题的无缝切换
  • 主题配置的统一管理与持久化
  • 通用组件的主题化封装
  • 响应式布局与自适应设计

2. 系统架构设计

2.1 架构概述

我们设计的主题管理系统采用分层架构,从底层配置到顶层组件形成完整的主题应用链路。系统主要包含以下几个核心模块:

  • 常量定义层:定义主题相关的常量,如主题模式、颜色类型、间距类型等
  • 配置层:定义具体的主题配置,包括颜色、间距、圆角、字体、阴影等
  • 管理层:提供主题切换、配置获取和持久化存储的核心功能
  • 组件层:封装通用 UI 组件,应用统一的主题样式

这种分层设计使得系统具有良好的可扩展性和可维护性,不同层次之间通过清晰的接口进行交互,实现了关注点分离。

2.2 核心模块关系

各模块之间的关系如下:

  1. ThemeConstants 定义基础常量,供其他模块使用
  2. ThemeConfig 基于常量定义具体的主题配置
  3. ThemeManager 负责主题切换、配置获取和持久化
  4. StyleManager 基于 ThemeManager 提供更高级别的样式管理
  5. 主题化组件(如 ThemeButton、ThemeCard)通过 StyleManager 获取样式

通过这种设计,我们实现了主题配置与组件实现的解耦,使得主题的修改和扩展变得简单高效。

3. 核心代码实现

3.1 常量定义(ThemeConstants)

首先,我们定义了主题相关的常量,为整个系统提供基础支持:

ThemeConstants.ets

/**
 * 主题常量定义
 */

/**
 * 主题模式类型
 */
export const THEME_MODE = {
  // 浅色模式
  LIGHT: 'light',
  // 深色模式
  DARK: 'dark',
  // 跟随系统
  AUTO: 'auto'
};

/**
 * 主题颜色类型
 */
export const COLOR_TYPE = {
  // 主题色
  PRIMARY: 'primary',
  ON_PRIMARY: 'onPrimary',
  PRIMARY_CONTAINER: 'primaryContainer',
  ON_PRIMARY_CONTAINER: 'onPrimaryContainer',
  // 背景色
  BACKGROUND: 'background',
  SURFACE: 'surface',
  SURFACE_VARIANT: 'surfaceVariant',
  // 文本色
  ON_SURFACE: 'onSurface',
  ON_SURFACE_VARIANT: 'onSurfaceVariant',
  // 边框色
  OUTLINE: 'outline',
  // 状态色
  ERROR: 'error',
  SUCCESS: 'success',
  WARNING: 'warning',
  INFO: 'info',
  DISABLED: 'disabled',
  // 其他颜色
  DIALOG_BG_WHITE: 'dialogBgWhite'
};

/**
 * 间距类型
 */
export const SPACING_TYPE = {
  NONE: 'none',
  TINY: 'tiny',
  SMALL: 'small',
  MEDIUM: 'medium',
  LARGE: 'large',
  XLARGE: 'xlarge',
  XXLARGE: 'xxlarge'
};

/**
 * 圆角类型
 */
export const RADIUS_TYPE = {
  NONE: 'none',
  SMALL: 'small',
  MEDIUM: 'medium',
  LARGE: 'large',
  XLARGE: 'xlarge',
  FULL: 'full'
};

/**
 * 字体大小类型
 */
export const FONT_SIZE_TYPE = {
  H1: 'h1',
  H2: 'h2',
  H3: 'h3',
  H4: 'h4',
  H5: 'h5',
  BODY1: 'body1',
  BODY2: 'body2',
  BODY3: 'body3',
  CAPTION: 'caption',
  CAPTION2: 'caption2'
};

/**
 * 阴影类型
 */
export const SHADOW_TYPE = {
  NONE: 'none',
  SMALL: 'small',
  MEDIUM: 'medium',
  LARGE: 'large'
};

/**
 * 导出所有常量
 */
export const ThemeConstants = {
  THEME_MODE,
  COLOR_TYPE,
  SPACING_TYPE,
  RADIUS_TYPE,
  FONT_SIZE_TYPE,
  SHADOW_TYPE
};

3.2 主题配置(ThemeConfig)

接下来,我们定义了具体的主题配置,包括浅色和深色两种模式。

ThemeConfig.ets

/**
 * 主题配置
 */
import { ThemeConstants } from '../constants/ThemeConstants';

/**
 * 颜色配置接口
 */
export interface ColorConfig {
  [key: string]: string;
}

/**
 * 间距配置接口
 */
export interface SpacingConfig {
  [key: string]: number;
}

/**
 * 圆角配置接口
 */
export interface RadiusConfig {
  [key: string]: number;
}

/**
 * 字体配置接口
 */
export interface FontConfig {
  [key: string]: number;
}

/**
 * 阴影配置接口
 */
export interface ShadowConfig {
  [key: string]: string;
}

/**
 * 主题配置接口
 */
export interface ThemeConfig {
  colors: ColorConfig;
  spacing: SpacingConfig;
  radius: RadiusConfig;
  fontSizes: FontConfig;
  shadows: ShadowConfig;
}

/**
 * 浅色主题配置
 */
export const lightTheme: ThemeConfig = {
  colors: {
    // 主题色
    [ThemeConstants.COLOR_TYPE.PRIMARY]: '#007dff',
    [ThemeConstants.COLOR_TYPE.ON_PRIMARY]: '#ffffff',
    [ThemeConstants.COLOR_TYPE.PRIMARY_CONTAINER]: '#e3f2fd',
    [ThemeConstants.COLOR_TYPE.ON_PRIMARY_CONTAINER]: '#001e3c',
    // 背景色
    [ThemeConstants.COLOR_TYPE.BACKGROUND]: '#F1F3F5',
    [ThemeConstants.COLOR_TYPE.SURFACE]: '#ffffff',
    [ThemeConstants.COLOR_TYPE.SURFACE_VARIANT]: '#f5f5f5',
    // 文本色
    [ThemeConstants.COLOR_TYPE.ON_SURFACE]: '#191919',
    [ThemeConstants.COLOR_TYPE.ON_SURFACE_VARIANT]: '#666666',
    // 边框色
    [ThemeConstants.COLOR_TYPE.OUTLINE]: '#e0e0e0',
    // 状态色
    [ThemeConstants.COLOR_TYPE.ERROR]: '#f44336',
    [ThemeConstants.COLOR_TYPE.SUCCESS]: '#4caf50',
    [ThemeConstants.COLOR_TYPE.WARNING]: '#ff9800',
    [ThemeConstants.COLOR_TYPE.INFO]: '#2196f3',
    [ThemeConstants.COLOR_TYPE.DISABLED]: '#9e9e9e',
    // 其他颜色
    [ThemeConstants.COLOR_TYPE.DIALOG_BG_WHITE]: '#ffffff'
  },
  spacing: {
    [ThemeConstants.SPACING_TYPE.NONE]: 0,
    [ThemeConstants.SPACING_TYPE.TINY]: 4,
    [ThemeConstants.SPACING_TYPE.SMALL]: 8,
    [ThemeConstants.SPACING_TYPE.MEDIUM]: 16,
    [ThemeConstants.SPACING_TYPE.LARGE]: 24,
    [ThemeConstants.SPACING_TYPE.XLARGE]: 32,
    [ThemeConstants.SPACING_TYPE.XXLARGE]: 48
  },
  radius: {
    [ThemeConstants.RADIUS_TYPE.NONE]: 0,
    [ThemeConstants.RADIUS_TYPE.SMALL]: 4,
    [ThemeConstants.RADIUS_TYPE.MEDIUM]: 8,
    [ThemeConstants.RADIUS_TYPE.LARGE]: 12,
    [ThemeConstants.RADIUS_TYPE.XLARGE]: 16,
    [ThemeConstants.RADIUS_TYPE.FULL]: 999
  },
  fontSizes: {
    [ThemeConstants.FONT_SIZE_TYPE.H1]: 32,
    [ThemeConstants.FONT_SIZE_TYPE.H2]: 28,
    [ThemeConstants.FONT_SIZE_TYPE.H3]: 24,
    [ThemeConstants.FONT_SIZE_TYPE.H4]: 20,
    [ThemeConstants.FONT_SIZE_TYPE.H5]: 18,
    [ThemeConstants.FONT_SIZE_TYPE.BODY1]: 16,
    [ThemeConstants.FONT_SIZE_TYPE.BODY2]: 14,
    [ThemeConstants.FONT_SIZE_TYPE.BODY3]: 12,
    [ThemeConstants.FONT_SIZE_TYPE.CAPTION]: 12,
    [ThemeConstants.FONT_SIZE_TYPE.CAPTION2]: 10
  },
  shadows: {
    [ThemeConstants.SHADOW_TYPE.NONE]: '',
    [ThemeConstants.SHADOW_TYPE.SMALL]: '0 2px 4px rgba(0, 0, 0, 0.05)',
    [ThemeConstants.SHADOW_TYPE.MEDIUM]: '0 4px 8px rgba(0, 0, 0, 0.1)',
    [ThemeConstants.SHADOW_TYPE.LARGE]: '0 8px 16px rgba(0, 0, 0, 0.12)'
  }
};

/**
 * 深色主题配置
 */
export const darkTheme: ThemeConfig = {
  colors: {
    // 主题色
    [ThemeConstants.COLOR_TYPE.PRIMARY]: '#64b5f6',
    [ThemeConstants.COLOR_TYPE.ON_PRIMARY]: '#002171',
    [ThemeConstants.COLOR_TYPE.PRIMARY_CONTAINER]: '#003399',
    [ThemeConstants.COLOR_TYPE.ON_PRIMARY_CONTAINER]: '#bbdefb',
    // 背景色
    [ThemeConstants.COLOR_TYPE.BACKGROUND]: '#121212',
    [ThemeConstants.COLOR_TYPE.SURFACE]: '#1e1e1e',
    [ThemeConstants.COLOR_TYPE.SURFACE_VARIANT]: '#2d2d2d',
    // 文本色
    [ThemeConstants.COLOR_TYPE.ON_SURFACE]: '#ffffff',
    [ThemeConstants.COLOR_TYPE.ON_SURFACE_VARIANT]: '#b0b0b0',
    // 边框色
    [ThemeConstants.COLOR_TYPE.OUTLINE]: '#404040',
    // 状态色
    [ThemeConstants.COLOR_TYPE.ERROR]: '#ef5350',
    [ThemeConstants.COLOR_TYPE.SUCCESS]: '#66bb6a',
    [ThemeConstants.COLOR_TYPE.WARNING]: '#ffa726',
    [ThemeConstants.COLOR_TYPE.INFO]: '#42a5f5',
    [ThemeConstants.COLOR_TYPE.DISABLED]: '#757575',
    // 其他颜色
    [ThemeConstants.COLOR_TYPE.DIALOG_BG_WHITE]: '#2c2c2c'
  },
  spacing: {
    [ThemeConstants.SPACING_TYPE.NONE]: 0,
    [ThemeConstants.SPACING_TYPE.TINY]: 4,
    [ThemeConstants.SPACING_TYPE.SMALL]: 8,
    [ThemeConstants.SPACING_TYPE.MEDIUM]: 16,
    [ThemeConstants.SPACING_TYPE.LARGE]: 24,
    [ThemeConstants.SPACING_TYPE.XLARGE]: 32,
    [ThemeConstants.SPACING_TYPE.XXLARGE]: 48
  },
  radius: {
    [ThemeConstants.RADIUS_TYPE.NONE]: 0,
    [ThemeConstants.RADIUS_TYPE.SMALL]: 4,
    [ThemeConstants.RADIUS_TYPE.MEDIUM]: 8,
    [ThemeConstants.RADIUS_TYPE.LARGE]: 12,
    [ThemeConstants.RADIUS_TYPE.XLARGE]: 16,
    [ThemeConstants.RADIUS_TYPE.FULL]: 999
  },
  fontSizes: {
    [ThemeConstants.FONT_SIZE_TYPE.H1]: 32,
    [ThemeConstants.FONT_SIZE_TYPE.H2]: 28,
    [ThemeConstants.FONT_SIZE_TYPE.H3]: 24,
    [ThemeConstants.FONT_SIZE_TYPE.H4]: 20,
    [ThemeConstants.FONT_SIZE_TYPE.H5]: 18,
    [ThemeConstants.FONT_SIZE_TYPE.BODY1]: 16,
    [ThemeConstants.FONT_SIZE_TYPE.BODY2]: 14,
    [ThemeConstants.FONT_SIZE_TYPE.BODY3]: 12,
    [ThemeConstants.FONT_SIZE_TYPE.CAPTION]: 12,
    [ThemeConstants.FONT_SIZE_TYPE.CAPTION2]: 10
  },
  shadows: {
    [ThemeConstants.SHADOW_TYPE.NONE]: '',
    [ThemeConstants.SHADOW_TYPE.SMALL]: '0 2px 4px rgba(0, 0, 0, 0.2)',
    [ThemeConstants.SHADOW_TYPE.MEDIUM]: '0 4px 8px rgba(0, 0, 0, 0.3)',
    [ThemeConstants.SHADOW_TYPE.LARGE]: '0 8px 16px rgba(0, 0, 0, 0.4)'
  }
};

/**
 * 导出主题配置
 */
export const ThemeConfigs = {
  light: lightTheme,
  dark: darkTheme
};

3.3 主题管理器(ThemeManager)

ThemeManager 是系统的核心,负责主题的切换、配置获取和持久化存储。

主题切换与应用流程

展示了从用户切换主题到系统应用主题样式的完整流程,包括主题模式变更、配置加载、持久化存储和组件更新等环节。

用户切换主题模式ThemeManager.setColorMode()更新主题配置保存到 AppStorage。

颜色配置参照配置表如下所示:

代码如下:

ThemeManager.ets

/**
 * 主题管理器
 */
import { AppStorage } from '@kit.ArkData';
import { GlobalContext } from '@kit.ArkUI';
import { Configuration } from '@kit.ArkUI';
import { CommonConstants } from '../constants/CommonContants';
import { ThemeConstants } from '../constants/ThemeConstants';
import { ThemeConfig, ThemeConfigs } from '../config/ThemeConfig';

/**
 * 主题管理器类
 */
export class ThemeManager {
  /**
   * 单例实例
   */
  private static instance: ThemeManager;
  
  /**
   * 当前主题配置
   */
  private currentTheme: ThemeConfig;
  
  /**
   * 是否为深色模式
   */
  private _isDarkMode: boolean = false;
  
  /**
   * 是否跟随系统设置
   */
  private _isFollowSystemSetting: boolean = true;
  
  /**
   * 配置变更监听回调
   */
  private onConfigChangeCallback: () => void = () => {};
  
  /**
   * 私有构造函数
   */
  private constructor() {
    // 初始化主题
    this.initializeTheme();
    // 监听系统主题变化
    this.listenSystemThemeChange();
  }
  
  /**
   * 获取单例实例
   */
  public static get instance(): ThemeManager {
    if (!this.instance) {
      this.instance = new ThemeManager();
    }
    return this.instance;
  }
  
  /**
   * 初始化主题
   */
  private initializeTheme(): void {
    // 从持久化存储中获取主题设置
    const savedThemeMode = AppStorage.getString(CommonConstants.THEME_MODE_KEY);
    
    if (savedThemeMode === ThemeConstants.THEME_MODE.LIGHT) {
      this._isFollowSystemSetting = false;
      this._isDarkMode = false;
      this.currentTheme = ThemeConfigs.light;
    } else if (savedThemeMode === ThemeConstants.THEME_MODE.DARK) {
      this._isFollowSystemSetting = false;
      this._isDarkMode = true;
      this.currentTheme = ThemeConfigs.dark;
    } else {
      // 默认跟随系统
      this._isFollowSystemSetting = true;
      const systemDarkMode = this.getSystemDarkMode();
      this._isDarkMode = systemDarkMode;
      this.currentTheme = systemDarkMode ? ThemeConfigs.dark : ThemeConfigs.light;
    }
  }
  
  /**
   * 获取系统深色模式状态
   */
  private getSystemDarkMode(): boolean {
    const configuration = GlobalContext.getContext().getObject('application')?.getConfiguration() as Configuration;
    return configuration?.colorMode === Configuration.ColorMode.COLOR_MODE_DARK;
  }
  
  /**
   * 监听系统主题变化
   */
  private listenSystemThemeChange(): void {
    GlobalContext.getContext().getObject('application')?.on('onConfigurationUpdated', (newConfig: Configuration) => {
      if (this._isFollowSystemSetting && newConfig?.colorMode) {
        const systemDarkMode = newConfig.colorMode === Configuration.ColorMode.COLOR_MODE_DARK;
        if (systemDarkMode !== this._isDarkMode) {
          this._isDarkMode = systemDarkMode;
          this.currentTheme = systemDarkMode ? ThemeConfigs.dark : ThemeConfigs.light;
          this.notifyConfigChange();
        }
      }
    });
  }
  
  /**
   * 设置颜色模式
   * @param isDark 是否为深色模式
   */
  public setColorMode(isDark: boolean): void {
    this._isDarkMode = isDark;
    this._isFollowSystemSetting = false;
    this.currentTheme = isDark ? ThemeConfigs.dark : ThemeConfigs.light;
    
    // 保存设置到持久化存储
    AppStorage.setOrCreate(CommonConstants.THEME_MODE_KEY, isDark ? ThemeConstants.THEME_MODE.DARK : ThemeConstants.THEME_MODE.LIGHT);
    
    // 通知配置变更
    this.notifyConfigChange();
  }
  
  /**
   * 设置自动颜色模式(跟随系统)
   */
  public setAutoColorMode(): void {
    this._isFollowSystemSetting = true;
    const systemDarkMode = this.getSystemDarkMode();
    this._isDarkMode = systemDarkMode;
    this.currentTheme = systemDarkMode ? ThemeConfigs.dark : ThemeConfigs.light;
    
    // 保存设置到持久化存储
    AppStorage.setOrCreate(CommonConstants.THEME_MODE_KEY, ThemeConstants.THEME_MODE.AUTO);
    
    // 通知配置变更
    this.notifyConfigChange();
  }
  
  /**
   * 获取颜色
   * @param colorType 颜色类型
   * @returns 颜色值
   */
  public getColor(colorType: string): string {
    return this.currentTheme.colors[colorType] || '#000000';
  }
  
  /**
   * 获取间距
   * @param spacingType 间距类型
   * @returns 间距值
   */
  public getSpacing(spacingType: string): number {
    return this.currentTheme.spacing[spacingType] || 0;
  }
  
  /**
   * 获取圆角
   * @param radiusType 圆角类型
   * @returns 圆角值
   */
  public getRadius(radiusType: string): number {
    return this.currentTheme.radius[radiusType] || 0;
  }
  
  /**
   * 获取字体大小
   * @param fontSizeType 字体大小类型
   * @returns 字体大小值
   */
  public getFontSize(fontSizeType: string): number {
    return this.currentTheme.fontSizes[fontSizeType] || 16;
  }
  
  /**
   * 获取阴影
   * @param shadowType 阴影类型
   * @returns 阴影值
   */
  public getShadow(shadowType: string): string {
    return this.currentTheme.shadows[shadowType] || '';
  }
  
  /**
   * 注册配置变更监听
   * @param callback 回调函数
   */
  public registerConfigChangeListener(callback: () => void): void {
    this.onConfigChangeCallback = callback;
  }
  
  /**
   * 通知配置变更
   */
  private notifyConfigChange(): void {
    this.onConfigChangeCallback();
  }
  
  /**
   * 获取当前是否为深色模式
   */
  public get isDarkMode(): boolean {
    return this._isDarkMode;
  }
  
  /**
   * 获取当前是否跟随系统设置
   */
  public get isFollowSystemSetting(): boolean {
    return this._isFollowSystemSetting;
  }
}

3.4 样式管理器(StyleManager)

StyleManager 提供了更高级别的样式管理功能,包括预定义组件样式和动态样式生成。

StyleManager.ets

/**
 * 样式管理器
 */
import { ThemeManager } from './ThemeManager';
import { ThemeConstants } from '../constants/ThemeConstants';

/**
 * 样式管理器类
 */
export class StyleManager {
  /**
   * 单例实例
   */
  private static instance: StyleManager;
  
  /**
   * 主题管理器
   */
  public themeManager: ThemeManager;
  
  /**
   * 私有构造函数
   */
  private constructor() {
    this.themeManager = ThemeManager.instance;
  }
  
  /**
   * 获取单例实例
   */
  public static get instance(): StyleManager {
    if (!this.instance) {
      this.instance = new StyleManager();
    }
    return this.instance;
  }
  
  /**
   * 获取容器样式
   */
  public getContainerStyle(): object {
    return {
      backgroundColor: this.themeManager.getColor(ThemeConstants.COLOR_TYPE.BACKGROUND),
      color: this.themeManager.getColor(ThemeConstants.COLOR_TYPE.ON_SURFACE)
    };
  }
  
  /**
   * 获取卡片样式
   * @param radiusType 圆角类型
   * @param shadowType 阴影类型
   */
  public getCardStyle(radiusType: string = ThemeConstants.RADIUS_TYPE.MEDIUM, shadowType: string = ThemeConstants.SHADOW_TYPE.MEDIUM): object {
    return {
      backgroundColor: this.themeManager.getColor(ThemeConstants.COLOR_TYPE.SURFACE),
      borderRadius: this.themeManager.getRadius(radiusType),
      shadow: this.themeManager.getShadow(shadowType),
      borderWidth: 0
    };
  }
  
  /**
   * 获取主要按钮样式
   * @param size 按钮大小
   */
  public getPrimaryButtonStyle(size: string = 'medium'): object {
    const paddingVertical = size === 'small' ? 6 : size === 'large' ? 16 : 10;
    const paddingHorizontal = size === 'small' ? 12 : size === 'large' ? 24 : 16;
    
    return {
      backgroundColor: this.themeManager.getColor(ThemeConstants.COLOR_TYPE.PRIMARY),
      borderRadius: this.themeManager.getRadius(ThemeConstants.RADIUS_TYPE.MEDIUM),
      paddingVertical,
      paddingHorizontal,
      alignItems: HorizontalAlign.Center,
      justifyContent: FlexAlign.Center
    };
  }
  
  /**
   * 获取次要按钮样式
   * @param size 按钮大小
   */
  public getSecondaryButtonStyle(size: string = 'medium'): object {
    const paddingVertical = size === 'small' ? 6 : size === 'large' ? 16 : 10;
    const paddingHorizontal = size === 'small' ? 12 : size === 'large' ? 24 : 16;
    
    return {
      backgroundColor: 'transparent',
      borderRadius: this.themeManager.getRadius(ThemeConstants.RADIUS_TYPE.MEDIUM),
      borderWidth: 1,
      borderColor: this.themeManager.getColor(ThemeConstants.COLOR_TYPE.PRIMARY),
      paddingVertical,
      paddingHorizontal,
      alignItems: HorizontalAlign.Center,
      justifyContent: FlexAlign.Center
    };
  }
  
  /**
   * 获取主要按钮文本样式
   * @param size 按钮大小
   */
  public getPrimaryButtonTextStyle(size: string = 'medium'): object {
    const fontSize = size === 'small' ? ThemeConstants.FONT_SIZE_TYPE.CAPTION : 
                     size === 'large' ? ThemeConstants.FONT_SIZE_TYPE.BODY1 : ThemeConstants.FONT_SIZE_TYPE.BODY2;
    
    return {
      color: this.themeManager.getColor(ThemeConstants.COLOR_TYPE.ON_PRIMARY),
      fontSize: this.themeManager.getFontSize(fontSize),
      fontWeight: 600
    };
  }
  
  /**
   * 获取次要按钮文本样式
   * @param size 按钮大小
   */
  public getSecondaryButtonTextStyle(size: string = 'medium'): object {
    const fontSize = size === 'small' ? ThemeConstants.FONT_SIZE_TYPE.CAPTION : 
                     size === 'large' ? ThemeConstants.FONT_SIZE_TYPE.BODY1 : ThemeConstants.FONT_SIZE_TYPE.BODY2;
    
    return {
      color: this.themeManager.getColor(ThemeConstants.COLOR_TYPE.PRIMARY),
      fontSize: this.themeManager.getFontSize(fontSize),
      fontWeight: 500
    };
  }
  
  /**
   * 获取文本样式
   * @param variant 文本变体
   * @param fontWeight 字体粗细
   */
  public getTextStyle(variant: string = ThemeConstants.FONT_SIZE_TYPE.BODY1, fontWeight: string = 'normal'): object {
    // 映射字体粗细
    let weight: number;
    switch (fontWeight) {
      case 'medium':
        weight = 500;
        break;
      case 'semiBold':
        weight = 600;
        break;
      case 'bold':
        weight = 700;
        break;
      default:
        weight = 400;
    }
    
    return {
      fontSize: this.themeManager.getFontSize(variant),
      fontWeight: weight
    };
  }
  
  /**
   * 获取输入框样式
   */
  public getInputStyle(): object {
    return {
      backgroundColor: this.themeManager.getColor(ThemeConstants.COLOR_TYPE.SURFACE),
      borderColor: this.themeManager.getColor(ThemeConstants.COLOR_TYPE.OUTLINE),
      borderWidth: 1,
      borderRadius: this.themeManager.getRadius(ThemeConstants.RADIUS_TYPE.MEDIUM),
      paddingHorizontal: this.themeManager.getSpacing(ThemeConstants.SPACING_TYPE.MEDIUM),
      paddingVertical: this.themeManager.getSpacing(ThemeConstants.SPACING_TYPE.SMALL),
      color: this.themeManager.getColor(ThemeConstants.COLOR_TYPE.ON_SURFACE),
      fontSize: this.themeManager.getFontSize(ThemeConstants.FONT_SIZE_TYPE.BODY1)
    };
  }
  
  /**
   * 获取分割线样式
   */
  public getDividerStyle(): object {
    return {
      backgroundColor: this.themeManager.getColor(ThemeConstants.COLOR_TYPE.OUTLINE),
      height: 1
    };
  }
  
  /**
   * 获取阴影样式
   * @param shadowType 阴影类型
   */
  public getShadowStyle(shadowType: string = ThemeConstants.SHADOW_TYPE.MEDIUM): object {
    return {
      shadow: this.themeManager.getShadow(shadowType)
    };
  }
  
  /**
   * 生成间距样式
   * @param horizontal 水平间距类型
   * @param vertical 垂直间距类型
   */
  public getPaddingStyle(horizontal?: string, vertical?: string): object {
    const padding: object = {};
    
    if (horizontal) {
      padding.paddingHorizontal = this.themeManager.getSpacing(horizontal);
    }
    
    if (vertical) {
      padding.paddingVertical = this.themeManager.getSpacing(vertical);
    }
    
    return padding;
  }
  
  /**
   * 生成边距样式
   * @param horizontal 水平边距类型
   * @param vertical 垂直边距类型
   */
  public getMarginStyle(horizontal?: string, vertical?: string): object {
    const margin: object = {};
    
    if (horizontal) {
      margin.marginHorizontal = this.themeManager.getSpacing(horizontal);
    }
    
    if (vertical) {
      margin.marginVertical = this.themeManager.getSpacing(vertical);
    }
    
    return margin;
  }
}

4. 主题化组件开发

主题化组件与原生组件对比如下:

4.1 ThemeButton 组件

ThemeButton 是一个支持多类型、多尺寸的主题化按钮组件:

ThemeButton.ets (核心部分)

/**
 * 主题按钮组件
 */
import { StyleManager } from '../manager/StyleManager';
import { CommonConstants } from '../constants/CommonContants';

/**
 * 按钮类型
 */
export type ButtonType = 'primary' | 'secondary' | 'outline' | 'text';

/**
 * 按钮大小
 */
export type ButtonSize = 'small' | 'medium' | 'large';

/**
 * 按钮属性
 */
export interface ThemeButtonProps {
  type?: ButtonType;
  size?: ButtonSize;
  disabled?: boolean;
  loading?: boolean;
  block?: boolean;
  leftIcon?: ResourceStr;
  rightIcon?: ResourceStr;
  onClick?: () => void;
  children?: string | Child[];
}

/**
 * 主题按钮组件
 */
@ComponentV2
export struct ThemeButton {
  /**
   * 样式管理器
   */
  private styleManager: StyleManager = StyleManager.instance;
  
  /**
   * 组件属性
   */
  @Param props: ThemeButtonProps = {};
  
  /**
   * 构建按钮样式
   */
  private buildButtonStyle(): object {
    const {
      type = 'primary',
      size = 'medium',
      disabled = false,
      block = false
    } = this.props;
    
    let style: object;
    
    switch (type) {
      case 'primary':
        style = this.styleManager.getPrimaryButtonStyle(size);
        break;
      case 'secondary':
        style = {
          ...this.styleManager.getSecondaryButtonStyle(size),
          backgroundColor: this.styleManager.themeManager.getColor('surfaceVariant')
        };
        break;
      case 'outline':
        style = this.styleManager.getSecondaryButtonStyle(size);
        break;
      case 'text':
        style = {
          backgroundColor: 'transparent',
          borderRadius: this.styleManager.themeManager.getRadius('medium'),
          paddingVertical: size === 'small' ? 6 : size === 'large' ? 16 : 10,
          paddingHorizontal: size === 'small' ? 12 : size === 'large' ? 24 : 16
        };
        break;
    }
    
    // 添加块级元素样式
    if (block) {
      style = {
        ...style,
        width: '100%'
      };
    }
    
    // 添加禁用样式
    if (disabled) {
      style = {
        ...style,
        opacity: 0.6,
        backgroundColor: type === 'primary' || type === 'secondary' 
          ? this.styleManager.themeManager.getColor('disabled') 
          : type === 'outline' ? 'transparent' : style.backgroundColor,
        borderColor: type === 'outline' ? this.styleManager.themeManager.getColor('disabled') : undefined
      };
    }
    
    return style;
  }
  
  // 其他方法省略...
}

4.2 ThemeCard 组件

ThemeCard 提供了统一的卡片样式封装,支持不同的圆角和阴影配置:

ThemeCard.ets (核心部分)

/**
 * 主题卡片组件
 */
import { StyleManager } from '../manager/StyleManager';
import { ThemeConstants } from '../constants/ThemeConstants';

/**
 * 卡片属性
 */
export interface ThemeCardProps {
  children: Child;
  padding?: string;
  radius?: string;
  shadow?: string;
  onClick?: () => void;
  disabled?: boolean;
  style?: object;
}

/**
 * 主题卡片组件
 */
@ComponentV2
export struct ThemeCard {
  /**
   * 样式管理器
   */
  private styleManager: StyleManager = StyleManager.instance;
  
  /**
   * 组件属性
   */
  @Param props: ThemeCardProps = {
    children: () => {},
    padding: ThemeConstants.SPACING_TYPE.MEDIUM,
    radius: ThemeConstants.RADIUS_TYPE.MEDIUM,
    shadow: ThemeConstants.SHADOW_TYPE.MEDIUM,
    disabled: false
  };
  
  /**
   * 构建卡片样式
   */
  private buildCardStyle(): object {
    const {
      padding = ThemeConstants.SPACING_TYPE.MEDIUM,
      radius = ThemeConstants.RADIUS_TYPE.MEDIUM,
      shadow = ThemeConstants.SHADOW_TYPE.MEDIUM,
      disabled = false,
      style = {}
    } = this.props;
    
    // 基础卡片样式
    const baseStyle = {
      ...this.styleManager.getCardStyle(radius, shadow),
      padding: this.styleManager.themeManager.getSpacing(padding)
    };
    
    // 添加禁用样式
    if (disabled) {
      baseStyle.opacity = 0.6;
    }
    
    // 合并自定义样式
    return {
      ...baseStyle,
      ...style
    };
  }
  
  // 其他方法省略...
}

4.3 ThemeText 组件

ThemeText 提供了丰富的文本样式选项,支持多种变体和颜色:

ThemeText.ets (核心部分)

/**
 * 主题文本组件
 */
import { StyleManager } from '../manager/StyleManager';
import { ThemeConstants } from '../constants/ThemeConstants';

/**
 * 文本变体类型
 */
export type TextVariant = 
  | 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6' 
  | 'body1' | 'body2' | 'body3' 
  | 'caption' | 'caption2' 
  | 'label' | 'label2';

/**
 * 文本颜色类型
 */
export type TextColor = 
  | 'primary' | 'secondary' | 'tertiary' | 'disabled' 
  | 'error' | 'success' | 'warning' | 'info';

/**
 * 文本属性
 */
export interface ThemeTextProps {
  children: string | Child;
  variant?: TextVariant;
  color?: TextColor;
  fontWeight?: string;
  textAlign?: TextAlign;
  maxLines?: number;
  textOverflow?: TextOverflow;
  selectable?: boolean;
  style?: object;
}

/**
 * 主题文本组件
 */
@ComponentV2
export struct ThemeText {
  /**
   * 样式管理器
   */
  private styleManager: StyleManager = StyleManager.instance;
  
  /**
   * 组件属性
   */
  @Param props: ThemeTextProps = {
    children: '',
    variant: 'body1',
    color: 'primary',
    fontWeight: 'normal',
    textAlign: TextAlign.Start,
    selectable: false
  };
  
  /**
   * 构建文本样式
   */
  private buildTextStyle(): object {
    const {
      variant = 'body1',
      color = 'primary',
      fontWeight = 'normal',
      textAlign = TextAlign.Start,
      maxLines,
      textOverflow,
      style = {}
    } = this.props;
    
    // 基础文本样式
    const baseStyle = this.styleManager.getTextStyle(variant, fontWeight);
    
    // 添加颜色样式
    let colorValue: string;
    switch (color) {
      case 'primary':
        colorValue = this.styleManager.themeManager.getColor('onSurface');
        break;
      case 'secondary':
        colorValue = this.styleManager.themeManager.getColor('onSurfaceVariant');
        break;
      // 其他颜色类型...
    }
    
    // 合并样式
    return {
      ...baseStyle,
      color: colorValue,
      textAlign,
      maxLines,
      textOverflow,
      selectable: this.props.selectable,
      ...style
    };
  }
  
  // 其他方法省略...
}

5. 主题化组件使用示例

5.1 在页面中使用主题化组件

以下是在页面中使用我们的主题化组件的示例:

ThemeDemoPage.ets (核心部分)

/**
 * 主题演示页面
 */
import { ThemeManager } from '../manager/ThemeManager';
import { ThemeConstants } from '../constants/ThemeConstants';
import { ThemeButton } from '../components/ThemeButton';
import { ThemeCard } from '../components/ThemeCard';
import { ThemeText } from '../components/ThemeText';

/**
 * 主题演示页面组件
 */
@Entry
@Component
struct ThemeDemoPage {
  /**
   * 主题管理器
   */
  private themeManager: ThemeManager = ThemeManager.instance;
  
  /**
   * 当前主题模式
   */
  @State currentTheme: string = this.themeManager.isDarkMode ? '深色主题' : '浅色主题';
  
  /**
   * 切换主题模式
   */
  private toggleTheme(): void {
    const isDark = !this.themeManager.isDarkMode;
    this.themeManager.setColorMode(isDark);
    this.currentTheme = isDark ? '深色主题' : '浅色主题';
  }
  
  /**
   * 组件构建
   */
  build() {
    Column({
      alignItems: HorizontalAlign.Center,
      space: 20
    })
    .width('100%')
    .height('100%')
    .padding(20)
    .backgroundColor(this.themeManager.getColor('background')) {
      
      // 标题部分
      ThemeText({
        children: 'ArkTS 主题化管理演示',
        variant: 'h2',
        fontWeight: 'bold',
        textAlign: TextAlign.Center
      });
      
      // 主题切换控制
      Row({ alignItems: VerticalAlign.Center, space: 12 })
        .padding({ top: 10, bottom: 30 })
        .width('100%')
        .justifyContent(FlexAlign.Center) {
        
        ThemeButton({
          children: '浅色主题',
          type: 'secondary',
          size: 'medium',
          onClick: () => {
            this.themeManager.setColorMode(false);
            this.currentTheme = '浅色主题';
          }
        });
        
        ThemeButton({
          children: '深色主题',
          type: 'secondary',
          size: 'medium',
          onClick: () => {
            this.themeManager.setColorMode(true);
            this.currentTheme = '深色主题';
          }
        });
      }
      
      // 按钮展示区域
      ThemeCard({
        padding: ThemeConstants.SPACING_TYPE.LARGE,
        radius: ThemeConstants.RADIUS_TYPE.LARGE,
        shadow: ThemeConstants.SHADOW_TYPE.MEDIUM
      }) {
        // 卡片内容...
      }
      
      // 更多组件...
    }
  }
}

6. 最佳实践与优化建议

6.1 性能优化

  • 避免频繁的主题切换:主题切换会触发大量组件的重新渲染,应避免在短时间内频繁切换主题。
  • 使用缓存:对于频繁访问的样式,可以考虑在组件内部进行缓存,减少重复计算。
  • 按需引入:只引入项目中实际使用的组件和功能,避免不必要的代码加载。

6.2 可维护性提升

  • 遵循设计规范:建立统一的设计规范,并在主题配置中严格执行。
  • 组件化设计:将UI拆分为可复用的主题化组件,减少重复代码。
  • 文档完善:为主题系统和组件提供详细的文档,包括使用方法和示例。

6.3 扩展性考虑

  • 自定义主题:支持用户自定义主题颜色、字体等配置。
  • 多主题支持:除了浅色和深色主题外,可考虑支持更多的主题变体。
  • 主题导出与导入:支持主题配置的导出与导入,便于主题共享和备份。

7. 总结

通过本文介绍的主题化管理系统,我们实现了在 ArkTS 应用中统一管理界面风格的目标。该系统具有以下优势:

  • 统一的设计语言:确保应用各部分风格一致,提升用户体验。
  • 灵活的主题切换:支持浅色/深色主题以及跟随系统设置。
  • 可复用的组件库:提供了一系列主题化组件,简化开发过程。
  • 易于维护和扩展:分层架构设计使得系统易于维护和扩展。

在实际开发中,我们建议结合项目的具体需求和设计规范,对主题系统进行适当的调整和优化。同时,随着 HarmonyOS 和 ArkTS 的不断发展,我们也应该关注新特性的应用,持续改进我们的主题化解决方案。

Logo

作为“人工智能6S店”的官方数字引擎,为AI开发者与企业提供一个覆盖软硬件全栈、一站式门户。

更多推荐