外观设置 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

相关推荐
BK贝壳27 分钟前
亿级用户签到位图选型复盘:用 bool-hybrid-array 扛冷启动打卡,也把它和 Roaring/Redis 的边界测清楚了
数据结构·python·性能优化·numpy
2601_966949652 小时前
如何根据研究的起止时间截取分钟级行情?Python 实战与 QuantDash 数据处理指南
开发语言·python·pandas·量化交易·1024程序员节·股票数据·quantdash
在世修行6 小时前
智学文枢:页面切换与跨页数据预填
python·桌面应用·signal·1024程序员节·pyside·跨页跳转·状态预填
2601_962885727 小时前
如何用 Python 把 K 线重采样成任意周期?
开发语言·python
打工仔折腾 AI7 小时前
在 Ubuntu ARM64 部署 Q1 V3.0 MuJoCo 模型:加载、单步推理与执行器响应解析
linux·运维·人工智能·python·深度学习·ubuntu·性能优化
信誓旦旦的程序猿8 小时前
【Python量化实战宝典 #21】北向资金跟随手册:聪明钱择时信号(Python 可跑)
python·1024程序员节·股票数据api·股票数据api接口·股票api数据接口·股票量化数据api·股票量化数据接口
严谨的麻辣烫8 小时前
静态 ISP 代理请求超时怎么排查?Python 与 curl 实战
python·http·requests·1024程序员节·网络排障
KeepRobots9 小时前
11-01 温哥华不回拨:用 60 行 Python 查你的工单系统会不会差一小时(KeepRobots 工程笔记)
python
xiao77mwq9 小时前
你以为 OCR 慢?实测 81.3 s 里全是故障代价:如何把「定格态」消掉,让耗时从 6.5 s 到 13 倍差距显出原形
python
深圳市益普科技有限公司10 小时前
半导体良率管理YMS:良率与设备参数的相关性,先拉哪几组数据
人工智能·python·算法