外观设置 Cordova 与 OpenHarmony 混合开发实战

📌 模块概述

外观设置功能允许用户自定义应用的外观,包括主题色、字体、背景等。用户可以根据自己的喜好来定制应用的外观。

🔗 完整流程

第一步:选择主题

用户选择喜欢的主题。

第二步:应用主题

主题被应用到整个应用。

第三步:保存偏好

用户的主题选择被保存。

🔧 Web代码实现

javascript 复制代码
async renderAppearance() {
  const settings = await noteDB.getSettings();

  return `
    <div class="page active">
      <div class="page-header">
        <h1 class="page-title">🎨 外观设置</h1>
      </div>
      <div class="appearance-settings">
        <div class="form-group">
          <label>主题</label>
          <div class="theme-options">
            <button class="theme-btn ${settings.theme === 'light' ? 'active' : ''}" onclick="app.setTheme('light')">浅色</button>
            <button class="theme-btn ${settings.theme === 'dark' ? 'active' : ''}" onclick="app.setTheme('dark')">深色</button>
          </div>
        </div>
        <div class="form-group">
          <label>主色</label>
          <input type="color" id="primary-color" value="${settings.primaryColor || '#409EFF'}" onchange="app.setPrimaryColor(this.value)">
        </div>
      </div>
    </div>
  `;
}

// 设置主题
async setTheme(theme) {
  try {
    const settings = await noteDB.getSettings();
    settings.theme = theme;
    await noteDB.updateSettings(settings);
    
    // 应用主题
    document.documentElement.setAttribute('data-theme', theme);
    
    Utils.showToast('主题已更改', 'success');
  } catch (error) {
    console.error('设置主题失败:', error);
  }
}

// 设置主色
async setPrimaryColor(color) {
  try {
    const settings = await noteDB.getSettings();
    settings.primaryColor = color;
    await noteDB.updateSettings(settings);
    
    // 应用颜色
    document.documentElement.style.setProperty('--primary-color', color);
    
    Utils.showToast('颜色已更改', 'success');
  } catch (error) {
    console.error('设置颜色失败:', error);
  }
}

🔌 OpenHarmony 原生代码

typescript 复制代码
// AppearancePlugin.ets - 外观设置插件
import { webview } from '@kit.ArkWeb';
import { common } from '@kit.AbilityKit';
import { fileIo } from '@kit.CoreFileKit';

@NativeComponent
export class AppearancePlugin {
  private context: common.UIAbilityContext;

  constructor(context: common.UIAbilityContext) {
    this.context = context;
  }

  // 初始化插件
  public init(webviewController: webview.WebviewController): void {
    webviewController.registerJavaScriptProxy(
      new AppearanceJSProxy(this),
      'appearancePlugin',
      ['setTheme', 'setPrimaryColor']
    );
  }

  // 设置主题
  public setTheme(theme: string): Promise<boolean> {
    return new Promise((resolve) => {
      try {
        const settingsPath = this.context.cacheDir + '/settings.json';
        let settings: any = { theme: 'light' };
        
        try {
          const content = fileIo.readTextSync(settingsPath);
          settings = JSON.parse(content);
        } catch {}
        
        settings.theme = theme;
        fileIo.writeTextSync(settingsPath, JSON.stringify(settings, null, 2));
        resolve(true);
      } catch (error) {
        console.error('Failed to set theme:', error);
        resolve(false);
      }
    });
  }

  // 设置主色
  public setPrimaryColor(color: string): Promise<boolean> {
    return new Promise((resolve) => {
      try {
        const settingsPath = this.context.cacheDir + '/settings.json';
        let settings: any = { primaryColor: '#409EFF' };
        
        try {
          const content = fileIo.readTextSync(settingsPath);
          settings = JSON.parse(content);
        } catch {}
        
        settings.primaryColor = color;
        fileIo.writeTextSync(settingsPath, JSON.stringify(settings, null, 2));
        resolve(true);
      } catch (error) {
        console.error('Failed to set primary color:', error);
        resolve(false);
      }
    });
  }
}

// AppearanceJSProxy.ets - JavaScript代理类
class AppearanceJSProxy {
  private plugin: AppearancePlugin;

  constructor(plugin: AppearancePlugin) {
    this.plugin = plugin;
  }

  setTheme(theme: string): void {
    this.plugin.setTheme(theme).then(success => {
      console.log('Theme set:', success);
    });
  }

  setPrimaryColor(color: string): void {
    this.plugin.setPrimaryColor(color).then(success => {
      console.log('Primary color set:', success);
    });
  }
}

📝 总结

外观设置功能展示了如何在Cordova与OpenHarmony混合开发中实现主题和颜色定制。

欢迎加入开源鸿蒙跨平台社区:https://openharmonycrossplatform.csdn.net

相关推荐
万笑佛24 分钟前
Python 实现Kafka SASL认证生产消费
python
m0_617493942 小时前
Python OpenCV 透视变换(Perspective Transform)详解与实战
开发语言·python·opencv
小李不困还能学2 小时前
PyCharm下载安装与配置教程
ide·python·pycharm
博观而约取厚积而薄发2 小时前
Pytest 从入门到精通,一篇就够(超详细实战教程)
python·测试工具·单元测试·自动化·pytest
imzed2 小时前
使用 Playwright + Pytest 构建 Web UI 自动化测试框架
python·自动化·pytest
普通网友2 小时前
pytest一些常见的插件
开发语言·python·pytest
时空系2 小时前
Python 高性能高压缩打包器 —— 基于 JianPy 语义分析引擎
python
cndes3 小时前
给Miniconda换源,让包下载更迅速
开发语言·python
Metaphor6923 小时前
使用 Python 添加、隐藏和删除 PDF 图层
python·pdf·图层