写点什么

鸿蒙开发:ArkUI 实现体重记录应用

作者:chengxujianke
  • 2025-05-22
    广东
  • 本文字数:1202 字

    阅读完需:约 4 分钟

最近在学习 HarmonyOS NEXT 的应用开发,尝试用 ArkUI 方舟开发框架做了一个简单的体重记录应用。这里记录一下开发过程中的一些心得。这个应用主要功能是让用户记录每日体重变化,并生成简单的趋势图表。ArkUI 的声明式开发方式确实让界面构建变得简单许多。首先创建了一个数据模型来存储体重记录:typescript


// 体重记录数据模型 class WeightRecord {date: string;weight: number;note: string;


constructor(date: string, weight: number, note: string) {this.date = date;this.weight = weight;this.note = note;}}


然后使用 ArkUI 的组件构建了主界面。这里发现 ArkUI 的 Column 和 Row 布局组件非常实用,配合 Flex 布局可以快速实现想要的界面效果:typescript


@Entry@Componentstruct WeightTrackerPage {@State weightRecords: WeightRecord[] = [];@State currentWeight: string = '';@State currentNote: string = '';


build() {Column() {// 标题 Text('体重记录').fontSize(24).fontWeight(FontWeight.Bold).margin({ bottom: 20 });


  // 输入区域  Row() {    TextInput({ placeholder: '输入体重(kg)' })      .width('60%')      .onChange((value: string) => {        this.currentWeight = value;      });        Button('添加记录')      .width('40%')      .onClick(() => {        if (this.currentWeight) {          const record = new WeightRecord(            new Date().toLocaleDateString(),            parseFloat(this.currentWeight),            this.currentNote          );          this.weightRecords.push(record);          this.currentWeight = '';          this.currentNote = '';        }      });  }.margin({ bottom: 10 });
// 记录列表 List({ space: 10 }) { ForEach(this.weightRecords, (item: WeightRecord) => { ListItem() { Column() { Text(`${item.date}: ${item.weight}kg`) if (item.note) { Text(`备注: ${item.note}`) .fontSize(12) .fontColor(Color.Gray); } } } }) }.layoutWeight(1) .divider({ strokeWidth: 1, color: '#F1F1F1' });}.padding(20).width('100%').height('100%');
复制代码


}}


在开发过程中,我发现 HarmonyOS NEXT 的 ArkUI 方舟开发框架对状态管理做得很好,@State 装饰器让数据变化能自动更新到 UI 上。API12 的兼容性也处理得不错,没有遇到明显的适配问题。图表展示部分我使用了 ArkUI 的 Canvas 组件来绘制简单的折线图,这里就不展开代码了。整体感觉 ArkUI 的学习曲线比较平缓,特别是对有前端开发经验的开发者来说。这个简单的体重记录应用还有不少可以改进的地方,比如加入数据持久化存储、更丰富的图表展示等。后续我会继续探索 HarmonyOS NEXT 的更多特性,逐步完善这个应用。

用户头像

chengxujianke

关注

还未添加个人签名 2025-03-07 加入

还未添加个人简介

评论

发布
暂无评论
鸿蒙开发:ArkUI实现体重记录应用_chengxujianke_InfoQ写作社区