#我的鸿蒙开发手记# HarmonyOS Next 计时器应用开发 原创

石头ovo
发布于 2025-5-5 18:40
浏览
0收藏

核心实现代码

@Entry
@Component
struct TimerPage {
  @State seconds: number = 0
  @State isRunning: boolean = false
  @State laps: string[] = []
  private timerId: number = -1

  // 时间格式化方法
  private formatTime(sec: number): string {
    const hours = Math.floor(sec / 3600)
    const minutes = Math.floor((sec % 3600) / 60)
    const seconds = sec % 60
    return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
  }

  // 定时器控制
  private startTimer() {
    this.timerId = setInterval(() => {
      this.seconds += 1
    }, 1000)
  }

  build() {
    Column({ space: 20 }) {
      // 时间显示
      Text(this.formatTime(this.seconds))
        .fontSize(40)
        .fontColor(Color.Black)

      // 控制按钮
      Row({ space: 15 }) {
        Button(this.isRunning ? '暂停' : '开始')
          .width(100)
          .onClick(() => {
            if (this.isRunning) {
              clearInterval(this.timerId)
            } else {
              this.startTimer()
            }
            this.isRunning = !this.isRunning
          })

        Button('重置')
          .width(100)
          .onClick(() => {
            this.seconds = 0
            this.laps = []
            clearInterval(this.timerId)
            this.isRunning = false
          })

        Button('记圈')
          .width(100)
          .onClick(() => {
            this.laps = [...this.laps, this.formatTime(this.seconds)]
          })
      }

      // 圈数记录
      List({ space: 10 }) {
        ForEach(this.laps, (item: string, index: number) => {
          ListItem() {
            Text(`第${index + 1}圈:${item}`)
              .fontSize(16)
              .margin(5)
          }
        })
      }
      .height('40%')
    }
    .width('100%')
    .height('100%')
    .padding(20)
  }

  // 清理定时器
  aboutToDisappear() {
    clearInterval(this.timerId)
  }
}

运行效果

#我的鸿蒙开发手记# HarmonyOS Next 计时器应用开发-鸿蒙开发者社区

功能解析

  1. 核心机制:
  • 使用setInterval创建1秒间隔的定时器
  • 通过@State管理计时状态(秒数、运行状态、圈数记录)
  • formatTime方法实现秒数到HH:MM:SS的格式转换
  1. UI组件:
    #我的鸿蒙开发手记# HarmonyOS Next 计时器应用开发-鸿蒙开发者社区
  2. 生命周期管理:
  • aboutToDisappear确保页面销毁时清除定时器
  • 避免内存泄漏

最后总结

基于ArkUI框架的计时器实现核心要点:

  1. 功能实现
  • 使用setInterval创建秒级定时器,通过@State管理计时秒数、运行状态及圈数记录
  • 事件绑定:开始/暂停、重置、记圈按钮触发状态变更
  • 时间格式化显示(HH:MM:SS),采用padStart补零优化显示
    关键技术
  • 状态驱动:@State装饰器实现数据到视图的自动更新
  • 生命周期:aboutToDisappear清理定时器防止内存泄漏
  • 列表渲染:ForEach动态生成圈数记录,支持滚动浏览
    使用DevEco Studio性能分析工具优化渲染效率

©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
已于2025-5-5 23:37:03修改
收藏
回复
举报
回复
    相关推荐