最近在学习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
@Component
struct 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的更多特性,逐步完善这个应用。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。