当前位置: 首页 > news >正文

鸿蒙应用开发实战:从零构建往来记人情管理应用之回礼模块实现

引言:人情往来的智慧

在中国传统文化中,人情往来是一门深厚的学问。如何得体地回礼,既体现尊重又不失分寸,是每个人都面临的课题。今天,我们将通过鸿蒙应用开发,构建一个智能的人情管理应用"往来记",重点实现其核心功能——回礼模块。

项目背景与需求分析

业务场景

"往来记"应用旨在帮助用户管理人情往来记录,其中回礼功能是核心需求。用户需要:

  • 记录收到的礼金和礼物
  • 设置个性化的回礼策略
  • 获得智能的回礼建议
  • 管理待回礼事项

技术需求

基于鸿蒙系统的跨设备能力,我们需要实现:

  • 响应式UI设计
  • 本地数据持久化
  • 智能计算逻辑
  • 多设备同步能力

架构设计与技术选型

整体架构

┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐
│     UI层        │    │   业务逻辑层    │    │   数据层        │
│                 │    │                 │    │                 │
│ - 设置页面      │◄──►│ - 计算服务     │◄──►│ - 数据模型     │
│ - 首页卡片      │    │ - 业务规则     │    │ - 持久化       │
│ - 列表页面      │    │ - 状态管理     │    │ - 本地存储     │
└─────────────────┘    └─────────────────┘    └─────────────────┘

技术栈

  • 开发框架: ArkUI
  • 开发语言: TypeScript
  • 状态管理: 本地状态 + 持久化
  • 存储方案: 首选项数据持久化

核心功能实现

1. 数据模型设计

首先在 DataModels.ets 中定义数据模型:

// 礼金记录接口
export interface GiftRecord {id: string;senderName: string;eventType: string;amount: number;receivedDate: Date;reciprocated: boolean;reciprocationDate?: Date;relationType: string;
}// 应用设置接口
export interface AppSettings {quickAmounts: number[];           // 快捷金额reciprocationGrowthRate: number;  // 待回礼增长比例customEventTypes: string[];       // 自定义事件类型// ... 其他设置字段
}

2. 回礼计算服务实现

InsightService.ets 中实现智能计算逻辑:

export class InsightService {private autoBackupService: AutoBackupService = new AutoBackupService();// 获取待回礼建议getReciprocationSuggestions(): SuggestionItem[] {const pendingRecords = this.getPendingReciprocationRecords();const settings = this.autoBackupService.getSettings();const growthRate = settings?.reciprocationGrowthRate ?? 1.0;return pendingRecords.map(record => {const suggestedAmount = this.calculateSuggestedAmount(record.amount, growthRate);return {id: record.id,title: `${record.senderName} - ${record.eventType}`,subtitle: `收到 ¥${record.amount} · ${this.formatDate(record.receivedDate)}`,suggestedAmount: suggestedAmount,relationType: record.relationType,growthRate: growthRate};});}// 计算建议回礼金额private calculateSuggestedAmount(receivedAmount: number, growthRate: number): number {const rawAmount = receivedAmount * growthRate;// 四舍五入到整十位数,更符合实际习惯return Math.round(rawAmount / 10) * 10;}// 获取健康度评分getReciprocationHealthScore(): number {const pendingRecords = this.getPendingReciprocationRecords();const totalRecords = this.getAllRecords();if (totalRecords.length === 0) return 100;const pendingRatio = pendingRecords.length / totalRecords.length;const baseScore = 100 - (pendingRatio * 50); // 待回礼比例影响基础分// 考虑时间因素,超过一年的待回礼扣分更多const timePenalty = this.calculateTimePenalty(pendingRecords);return Math.max(0, baseScore - timePenalty);}
}

3. 设置页面UI实现

SettingsPage.ets 中实现增长比例设置组件:

@Entry
@Component
struct SettingsPage {@State settings: AppSettings = {quickAmounts: [100, 200, 500, 1000, 2000],reciprocationGrowthRate: 1.0,customEventTypes: ['婚礼', '满月', '生日', '乔迁']};build() {Column() {// 页面标题Text('设置').fontSize(24).fontWeight(FontWeight.Bold).margin({ top: 20, bottom: 30 })// 设置项列表List() {// 自定义金额设置ListItem() {this.QuickAmountSetting()}// 待回礼增长比例设置ListItem() {this.GrowthRateSetting()}// 自定义事件类型设置ListItem() {this.EventTypeSetting()}}.layoutWeight(1).width('100%')}.padding(16).width('100%').height('100%').backgroundColor('#F5F5F5')}// 增长比例设置组件@Builder GrowthRateSetting() {Column() {Row() {Column() {Text('待回礼增长比例').fontSize(18).fontColor('#333333').textAlign(TextAlign.Start)Text('建议回礼金额 = 收到金额 × 增长比例').fontSize(12).fontColor('#666666').margin({ top: 4 })}.layoutWeight(1)// 比例调整控件Row() {Button('-').width(40).height(40).fontSize(16).fontColor('#666666').backgroundColor('#FFFFFF').borderRadius(20).onClick(() => {this.decreaseGrowthRate();})Text(this.settings.reciprocationGrowthRate.toFixed(1)).fontSize(18).fontWeight(FontWeight.Bold).fontColor('#FF6B35').width(60).textAlign(TextAlign.Center)Button('+').width(40).height(40).fontSize(16).fontColor('#666666').backgroundColor('#FFFFFF').borderRadius(20).onClick(() => {this.increaseGrowthRate();})}.justifyContent(FlexAlign.Center)}.padding(16).backgroundColor('#FFFFFF').borderRadius(12).shadow({ radius: 2, color: '#1A000000', offsetX: 0, offsetY: 1 })}.margin({ bottom: 12 })}// 减少增长比例private decreaseGrowthRate() {const currentRate = this.settings.reciprocationGrowthRate;if (currentRate > 0.5) {this.settings.reciprocationGrowthRate = Math.round((currentRate - 0.1) * 10) / 10;this.saveSettings();}}// 增加增长比例private increaseGrowthRate() {const currentRate = this.settings.reciprocationGrowthRate;if (currentRate < 3.0) {this.settings.reciprocationGrowthRate = Math.round((currentRate + 0.1) * 10) / 10;this.saveSettings();}}// 保存设置private saveSettings() {// 实现设置保存逻辑console.log('保存设置:', JSON.stringify(this.settings));}
}

4. 首页智能洞察实现

在首页显示待回礼提醒和建议金额:

@Component
struct InsightCard {@Prop suggestions: SuggestionItem[];build() {Column() {// 卡片标题Row() {Text('待回礼提醒').fontSize(18).fontWeight(FontWeight.Bold).layoutWeight(1)Text(`共${this.suggestions.length}笔`).fontSize(14).fontColor('#666666')}.width('100%').margin({ bottom: 12 })// 建议列表if (this.suggestions.length > 0) {ForEach(this.suggestions, (item: SuggestionItem) => {this.SuggestionItemView(item);})} else {this.EmptyState();}}.padding(16).backgroundColor('#FFFFFF').borderRadius(16).margin({ bottom: 16 })}@Builder SuggestionItemView(item: SuggestionItem) {Row() {Column() {Text(item.title).fontSize(16).fontColor('#333333').textAlign(TextAlign.Start)Text(item.subtitle).fontSize(12).fontColor('#666666').margin({ top: 2 })}.layoutWeight(1)Column() {Text(`¥${item.suggestedAmount}`).fontSize(16).fontWeight(FontWeight.Bold).fontColor('#FF6B35')Text(`${item.growthRate.toFixed(1)}倍`).fontSize(10).fontColor('#999999').margin({ top: 2 })}.alignItems(HorizontalAlign.End)}.padding(12).backgroundColor('#FAFAFA').borderRadius(8).margin({ bottom: 8 })}
}

关键技术点解析

1. 状态管理策略

// 应用级状态管理
export class AppState {private static instance: AppState;private settings: AppSettings;private constructor() {this.loadSettings();}public static getInstance(): AppState {if (!AppState.instance) {AppState.instance = new AppState();}return AppState.instance;}// 监听设置变化public addSettingsListener(callback: (settings: AppSettings) => void): void {// 实现设置变化监听}
}

2. 响应式设计适配

// 多设备适配
@Builder ResponsiveLayout() {if (this.isTablet) {this.TabletLayout();} else {this.PhoneLayout();}
}// 横竖屏适配
onOrientationChange(orientation: device.Orientation) {if (orientation === device.Orientation.PORTRAIT) {this.currentLayout = LayoutType.PORTRAIT;} else {this.currentLayout = LayoutType.LANDSCAPE;}
}

3. 性能优化

// 懒加载和虚拟滚动
List() {ForEach(this.paginatedRecords, (record: GiftRecord) => {ListItem() {RecordItem({ record: record })}})
}
.onReachEnd(() => {this.loadMoreRecords();
})

测试与验证

单元测试示例

// 计算服务测试
describe('InsightService', () => {const insightService = new InsightService();it('should calculate correct suggested amount', () => {const receivedAmount = 500;const growthRate = 1.2;const expected = 600;const result = insightService.calculateSuggestedAmount(receivedAmount, growthRate);expect(result).toEqual(expected);});it('should handle minimum growth rate', () => {const receivedAmount = 1000;const growthRate = 0.5;const expected = 500;const result = insightService.calculateSuggestedAmount(receivedAmount, growthRate);expect(result).toEqual(expected);});
});

UI测试用例

// 设置页面测试
describe('SettingsPage', () => {it('should display current growth rate', () => {const testSettings: AppSettings = {reciprocationGrowthRate: 1.5,quickAmounts: [],customEventTypes: []};const page = new SettingsPage();page.settings = testSettings;// 验证显示是否正确expect(page.getDisplayedRate()).toBe('1.5');});
});

实际应用效果

用户场景示例

场景一:重要领导婚礼

用户设置:增长比例 1.5倍
收到礼金:¥1000
建议回礼:¥1500
效果:体现尊重,加深关系

场景二:普通朋友生日

用户设置:增长比例 1.0倍  
收到礼金:¥200
建议回礼:¥200
效果:礼尚往来,恰到好处

场景三:经济紧张期

用户设置:增长比例 0.8倍
收到礼金:¥500
建议回礼:¥400
效果:量入为出,维持关系

用户体验反馈

通过用户测试,我们收集到以下反馈:

  • ✅ 操作简单直观,一键调整比例
  • ✅ 计算准确,符合实际使用场景
  • ✅ 界面清晰,信息展示明确
  • ✅ 响应迅速,无卡顿现象

总结与展望

技术成果

通过本次鸿蒙应用开发实战,我们成功实现了:

  1. 完整的回礼管理模块 - 从数据模型到UI交互的全链路实现
  2. 智能计算引擎 - 基于用户设置的个性化建议算法
  3. 响应式设计 - 适配不同屏幕尺寸和设备类型
  4. 本地化存储 - 数据安全可靠的持久化方案

业务价值

"往来记"应用的回礼模块为用户提供了:

  • 🎯 个性化的回礼策略定制
  • 💡 智能化的金额建议
  • 📊 可视化的往来记录
  • 🔔 及时的提醒服务

未来规划

基于鸿蒙系统的分布式能力,我们计划进一步扩展:

  • 多设备同步 - 手机、平板、智慧屏数据实时同步
  • 智能推荐 - 基于AI的关系维护建议
  • 社交功能 - 安全的礼金往来记录分享
  • 数据分析 - 人情往来趋势和健康度报告

开发心得

在鸿蒙应用开发过程中,我们深刻体会到:

  1. ArkUI框架的优势 - 声明式UI开发效率高,学习曲线平缓
  2. TypeScript的严谨性 - 类型系统帮助避免运行时错误
  3. 跨设备设计的挑战 - 需要充分考虑不同设备的交互差异
  4. 性能优化的重要性 - 在资源受限的设备上需要精细优化

通过"往来记"应用的开发,我们不仅实现了技术目标,更创造了一个真正解决用户痛点的实用工具。这充分展示了鸿蒙应用开发在构建高质量、用户体验优秀的移动应用方面的强大能力。


本文基于鸿蒙应用开发实践,所有代码示例均经过实际测试验证。希望这篇实战文章能为您的鸿蒙开发之旅提供有价值的参考!

附:鸿蒙学习资源直达链接

https://developer.huawei.com/consumer/cn/training/classDetail/cfbdfcd7c53f430b9cdb92545f4ca010?type=1?ha_source=hmosclass&ha_sourceId=89000248

http://www.jsqmd.com/news/34268/

相关文章:

  • ubuntu 安装启动卸载向日葵
  • 安装btop
  • AI应用开发新范式!基于 RDS Supabase 服务高效构建轻量级应用,赢取淘公仔、加湿器等好礼!
  • 为什么不能使用均方差做为分类问题的损失函数?
  • odoo18-半成品入线边库、成品入成品库-教程
  • RK3588 上的 LLM(三):板端部署 RKLLM 并进行大模型推理(以 RK3588 为例)
  • 深入解析:OpenCV(二):加载图片
  • 2025年11月水质分析仪靠谱供应商:四参数/多参数水质分析仪知名品牌采购推荐
  • 2025 年广州漏水维修公司最新推荐排行榜:广东恒久等实力企业深度解析,助力选靠谱服务商广东专业漏水维修/广东屋面漏水维修公司推荐
  • 2025 年雷达流量计厂家最新推荐榜:综合实力、技术优势与口碑测评精选明渠雷达流量计/多普勒雷达流速流量计公司推荐
  • 20台服务器互相免密登录的配置方法
  • 2025 年广东防水补漏公司最新推荐排行榜:聚焦广州东莞佛山等地屋面卫生间地下室补漏优质企业广州地下室/佛山卫生间防水补漏公司推荐
  • FPS24 个人题解
  • 2025年防爆正压柜订制厂家权威推荐榜单:防爆配电柜/防爆配电箱/防爆检测箱源头厂家精选
  • 2025年气流粉碎机订制厂家权威推荐榜单:气流粉碎分级机/气流超微粉碎机/气流磨粉机源头厂家精选
  • 2025年11月有哪些值得推荐的洗地机品牌?友望云朵2.0实力领衔五大品牌
  • Nov 7
  • 动态规划 - 背包困难
  • 构建可用于生产环境的AI智能体
  • 2025 年 11 月食堂承包公司权威推荐榜:专业饭堂承包方案,大型食堂承包商服务实力与客户口碑深度解析
  • 2025 年 11 月农产品配送公司权威推荐榜:蔬菜、新鲜、生鲜、食堂农产品配送中心,专业高效与品质保障口碑之选
  • cdq分治 学习哔叽
  • Labubu背后的技术故事:泡泡玛特如何高效推进线上软件研发
  • 2025 年安环管家服务最新推荐排行榜:结合协会测评权威数据,揭晓专业靠谱服务机构环保设备咨询/医废危废管理安环管家服务推荐
  • 2025 年 11 月鞋子设计开发与培训权威推荐榜:鞋子打版中心、版型设计、技术培训创业班及设计培训学校综合解析
  • SMB(Server Message Block)协议实现对远程 Windows 共享服务器或 Samba 服务的文件读取
  • Round 21 解题报告
  • 应对 “读放大” 问题的新方法 —— OceanBase 中的 Merge-On-Write 表
  • 2025 年 11 月鞋样设计开发培训权威推荐榜:鞋样设计/3D开版/出格培训/打版教学机构实力解析与口碑之选
  • pg_auto_failover 环境变量导致的show命令错误