《HarmonyOS Next开发进阶:打造功能完备的Todo应用华章》

章节 6:日期选择器与日期处理

目标
  • 学习如何使用DatePicker组件。
  • 理解日期格式化和日期计算。
内容
  1. 日期选择器基础
    • 使用DatePicker组件。
    • 处理日期选择事件。
  2. 日期格式化
    • 格式化日期为友好的文本。
  3. 日期计算
    • 判断日期是否过期或即将到期。
代码示例
typescript 复制代码
@Entry
@Component
struct DatePickerDemo {
  @State selectedDate: Date = new Date();
  @State showDatePicker: boolean = false;

  formatDate(date: Date): string {
    return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
  }

  build() {
    Column() {
      Text('选择日期: ' + this.formatDate(this.selectedDate))
        .margin({ bottom: 16 })

      Button('选择日期')
        .onClick(() => { this.showDatePicker = true; })

      if (this.showDatePicker) {
        DatePicker({
          start: new Date('2020-01-01'),
          end: new Date('2030-12-31'),
          selected: this.selectedDate,
        })
          .onChange((value: DatePickerInfo) => {
            this.selectedDate = new Date(value.year, value.month - 1, value.day);
          })
          .margin({ bottom: 16 })
      }
    }
  }
}

章节 7:任务统计与数据可视化

目标
  • 学习如何实现任务统计。
  • 理解简单的数据可视化方法。
内容
  1. 任务统计
    • 计算任务总数和完成率。
    • 按优先级统计任务数量。
  2. 数据可视化
    • 使用简单的图表展示统计数据。
  3. 示例:任务统计面板
    • 实现任务统计功能。
代码示例
typescript 复制代码
@Entry
@Component
struct TaskStatistics {
  @State todoList: TodoItem[] = [
    new TodoItem('任务1', Priority.HIGH),
    new TodoItem('任务2', Priority.MEDIUM),
    new TodoItem('任务3', Priority.LOW)
  ];

  getCompletionPercentage(): number {
    if (this.todoList.length === 0) return 0;
    const completedCount = this.todoList.filter(item => item.isCompleted).length;
    return Math.round((completedCount / this.todoList.length) * 100);
  }

  getPriorityStats(): PriorityStatItem[] {
    const highStat: PriorityStatItem = { priority: Priority.HIGH, count: 0, color: '#FF3B30' };
    const mediumStat: PriorityStatItem = { priority: Priority.MEDIUM, count: 0, color: '#FF9500' };
    const lowStat: PriorityStatItem = { priority: Priority.LOW, count: 0, color: '#34C759' };

    this.todoList.forEach(item => {
      switch (item.priority) {
        case Priority.HIGH: highStat.count++; break;
        case Priority.MEDIUM: mediumStat.count++; break;
        case Priority.LOW: lowStat.count++; break;
      }
    });

    return [highStat, mediumStat, lowStat];
  }

  build() {
    Column() {
      Text('任务统计')
        .fontSize(24)
        .fontWeight(FontWeight.Bold)
        .margin({ bottom: 16 })

      Text(`完成率: ${this.getCompletionPercentage()}%`)
        .margin({ bottom: 16 })

      ForEach(this.getPriorityStats(), (stat: PriorityStatItem) => {
        Row() {
          Circle()
            .fill(stat.color)
            .width(12)
            .height(12)
            .margin({ right: 8 })
          Text(`${stat.priority}: ${stat.count} 个`)
        }
        .margin({ bottom: 8 })
      })
    }
  }
}

章节 8:振动反馈与用户交互

目标
  • 学习如何使用@ohos.vibrator实现振动反馈。
  • 理解用户交互的优化方法。
内容
  1. 振动反馈基础
    • 使用vibrate方法实现短振动。
  2. 用户交互优化
    • 在任务操作时提供振动反馈。
  3. 示例:振动反馈应用
    • 实现用户交互时的振动效果。
代码示例
typescript 复制代码
import vibrator from '@ohos.vibrator';

@Entry
@Component
struct VibrationDemo {
  vibrateShort() {
    try {
      vibrator.vibrate(10);
    } catch (error) {
      console.error('Failed to vibrate:', error);
    }
  }

  build() {
    Column() {
      Text('点击按钮体验振动反馈')
        .margin({ bottom: 16 })

      Button('短振动')
        .onClick(() => this.vibrateShort())
    }
  }
}

章节 9:对话框与用户提示

目标
  • 学习如何使用@ohos.promptAction显示对话框。
  • 理解如何处理用户输入。
内容
  1. 对话框基础
    • 使用showDialog方法显示对话框。
  2. 用户输入处理
    • 获取用户选择的结果。
  3. 示例:确认删除对话框
    • 实现删除任务时的确认对话框。
代码示例
typescript 复制代码
import promptAction from '@ohos.promptAction';

@Entry
@Component
struct DialogDemo {
  async showConfirmationDialog() {
    try {
      const dialogButtons: Array<DialogButton> = [
        { text: '取消', color: '#8E8E93' },
        { text: '确定', color: '#FF3B30' }
      ];

      const options: promptAction.ShowDialogOptions = {
        title: '确认删除',
        message: '确定要删除此任务吗?',
        buttons: dialogButtons
      };

      const result = await promptAction.showDialog(options);
      if (result && result.index === 1) {
        console.log('用户确认删除');
      }
    } catch (error) {
      console.error('对话框显示失败:', error);
    }
  }

  build() {
    Column() {
      Text('点击按钮显示对话框')
        .margin({ bottom: 16 })

      Button('删除任务')
        .onClick(() => this.showConfirmationDialog())
    }
  }
}

章节 10:完整Todo应用实现

目标
  • 综合应用前面章节的知识,实现一个完整的Todo应用。
  • 理解如何将各个功能模块整合在一起。
内容
  1. 功能整合
    • 数据存储与加载。
    • 响应式布局与主题切换。
    • 任务管理与统计。
    • 日期选择与振动反馈。
  2. 完整代码实现
    • 从头到尾实现一个功能完整的Todo应用。
代码示例

(完整代码见用户提供的代码)

相关推荐
加农炮手Jinx9 小时前
Flutter for OpenHarmony 实战:flutter_animate 声明式动画让 UI 灵动如原生
flutter·ui·华为·harmonyos·鸿蒙
里欧跑得慢10 小时前
Flutter 三方库 function_tree — 鸿蒙应用开发中的动态数学公式解析与计算神器,实现鸿蒙深度适配下的复杂函数逻辑运行时求值实战(适配鸿蒙 HarmonyOS Next ohos)
android·前端·安全·flutter·华为·harmonyos
2501_9197490312 小时前
华为鸿蒙免费制定规则软件—小羊规则
华为·harmonyos·鸿蒙
lilian23313 小时前
HarmonyOS 7 新特性(四)|沉浸光感:空间材质、性能分级与降级策略
前端·pytorch·华为·harmonyos·材质
大雷神13 小时前
HarmonyOS AR Engine 物体形状实战:把实体书识别为 RECTANGLE,再放进地面 AR 盒子
ar·restful·harmonyos
AI备忘录14 小时前
(十六)GRE/IPSec 隧道配置命令五厂商对照:华为 华三 锐捷 迈普 思科
运维·服务器·网络·网络协议·网络安全·华为
BlueAsia_Lab15 小时前
华为 SuperCharge 认证,覆盖哪些产品?全品类梳理
运维·服务器·华为
OH_TPC17 小时前
HarmonyOS APP开发---"新鲜事"社交动态App,需要用到这个库
harmonyos
not coder17 小时前
我给鸿蒙原生 OFD 阅读器加了手写签批:手写笔防误触、矢量笔迹、批注追溯
华为·harmonyos·arkts·ofd
Magic-ZYJ19 小时前
HarmonyOS 页面生命周期完整梳理:aboutToAppear、onPageShow、onPageHide 别再混着用
华为·ts·harmonyos·移动应用开发·arcts·arcui