一、案例介绍

本案例将展示Progress组件在复杂业务场景中的应用,通过实现一个多任务进度管理系统,展示如何在实际项目中灵活运用Progress组件。

二、实现目标

  1. 创建多任务进度管理界面
  2. 实现任务进度的并行处理
  3. 添加任务状态管理和控制

三、代码实现

1. 任务管理界面

@Entry
@Component
struct TaskProgressExample {
  // 任务数据结构
  @State tasks: Array<{
    id: number,
    name: string,
    progress: number,
    status: 'pending' | 'running' | 'paused' | 'completed',
    type: 'normal' | 'important' | 'urgent'
  }> = [
    { id: 1, name: '数据同步', progress: 0, status: 'pending', type: 'normal' },
    { id: 2, name: '文件备份', progress: 0, status: 'pending', type: 'important' },
    { id: 3, name: '系统更新', progress: 0, status: 'pending', type: 'urgent' }
  ]

  @State activeTaskCount: number = 0
  private timers: Map<number, number> = new Map()

  build() {
    Column({ space: 20 }) {
      // 总体进度
      Row() {
        Text('总体进度')
          .fontSize(16)
          .fontWeight(FontWeight.Medium)
        
        Text(`${this.activeTaskCount}/${this.tasks.length} 任务进行中`)
          .fontSize(14)
          .margin({ left: 10 })
      }
      .width('100%')
      .justifyContent(FlexAlign.SpaceBetween)

      // 任务列表
      List({ space: 15 }) {
        ForEach(this.tasks, (task) => {
          ListItem() {
            this.TaskItem(task)
          }
        })
      }
      .width('100%')

      // 控制按钮
      Row({ space: 20 }) {
        Button('全部开始')
          .onClick(() => this.startAllTasks())

        Button('全部暂停')
          .onClick(() => this.pauseAllTasks())

        Button('重置')
          .onClick(() => this.resetAllTasks())
      }
      .margin({ top: 20 })
    }
    .width('100%')
    .height('100%')
    .padding(20)
    .backgroundColor('#FFFFFF')
  }

  @Builder
  TaskItem(task: {
    id: number,
    name: string,
    progress: number,
    status: string,
    type: string
  }) {
    Column({ space: 10 }) {
      Row() {
        Text(task.name)
          .fontSize(16)
          .fontWeight(FontWeight.Medium)

        Text(task.status)
          .fontSize(14)
          .fontColor(this.getStatusColor(task.status))
      }
      .width('100%')
      .justifyContent(FlexAlign.SpaceBetween)

      Stack({ alignContent: Alignment.Center }) {
        Progress({ value: task.progress, total: 100 })
          .width('100%')
          .height(15)
          .color(this.getTypeColor(task.type))
          .backgroundColor('#F5F5F5')

        Text(`${Math.floor(task.progress)}%`)
          .fontSize(12)
          .fontColor('#FFFFFF')
      }

      Row({ space: 10 }) {
        Button(task.status === 'running' ? '暂停' : '开始')
          .width(80)
          .height(30)
          .fontSize(14)
          .onClick(() => this.toggleTask(task.id))

        Button('重置')
          .width(80)
          .height(30)
          .fontSize(14)
          .onClick(() => this.resetTask(task.id))
      }
    }
    .width('100%')
    .padding(15)
    .borderRadius(10)
    .backgroundColor('#F8F8F8')
  }

  // 获取状态颜色
  getStatusColor(status: string) {
    switch (status) {
      case 'running':
        return '#4CAF50'
      case 'paused':
        return '#FFA000'
      case 'completed':
        return '#2196F3'
      default:
        return '#9E9E9E'
    }
  }

  // 获取任务类型颜色
  getTypeColor(type: string) {
    switch (type) {
      case 'urgent':
        return '#F44336'
      case 'important':
        return '#2196F3'
      default:
        return '#4CAF50'
    }
  }

  // 开始单个任务
  startTask(taskId: number) {
    const taskIndex = this.tasks.findIndex(t => t.id === taskId)
    if (taskIndex === -1) return

    const task = this.tasks[taskIndex]
    if (task.status === 'completed') return

    task.status = 'running'
    this.activeTaskCount++

    const timer = setInterval(() => {
      if (task.progress < 100) {
        task.progress += 1
        this.tasks[taskIndex] = { ...task }
      } else {
        task.status = 'completed'
        this.activeTaskCount--
        clearInterval(timer)
      }
    }, 100)

    this.timers.set(taskId, timer)
  }

  // 暂停任务
  pauseTask(taskId: number) {
    const taskIndex = this.tasks.findIndex(t => t.id === taskId)
    if (taskIndex === -1) return

    const task = this.tasks[taskIndex]
    if (task.status !== 'running') return

    task.status = 'paused'
    this.activeTaskCount--
    clearInterval(this.timers.get(taskId))
    this.timers.delete(taskId)
  }

  // 切换任务状态
  toggleTask(taskId: number) {
    const task = this.tasks.find(t => t.id === taskId)
    if (!task) return

    if (task.status === 'running') {
      this.pauseTask(taskId)
    } else {
      this.startTask(taskId)
    }
  }

  // 重置任务
  resetTask(taskId: number) {
    const taskIndex = this.tasks.findIndex(t => t.id === taskId)
    if (taskIndex === -1) return

    const task = this.tasks[taskIndex]
    if (task.status === 'running') {
      this.pauseTask(taskId)
    }

    task.progress = 0
    task.status = 'pending'
    this.tasks[taskIndex] = { ...task }
  }

  // 开始所有任务
  startAllTasks() {
    this.tasks.forEach(task => {
      if (task.status !== 'running' && task.status !== 'completed') {
        this.startTask(task.id)
      }
    })
  }

  // 暂停所有任务
  pauseAllTasks() {
    this.tasks.forEach(task => {
      if (task.status === 'running') {
        this.pauseTask(task.id)
      }
    })
  }

  // 重置所有任务
  resetAllTasks() {
    this.pauseAllTasks()
    this.tasks = this.tasks.map(task => ({
      ...task,
      progress: 0,
      status: 'pending'
    }))
  }

  aboutToDisappear() {
    this.timers.forEach(timer => clearInterval(timer))
    this.timers.clear()
  }
}

四、功能说明

1. 任务管理

  • 支持多任务并行处理
  • 任务状态管理
  • 进度实时更新

2. 交互控制

  • 单任务控制
  • 批量任务控制
  • 任务重置功能

3. 视觉反馈

  • 任务状态颜色区分
  • 进度实时显示
  • 任务类型标识

五、开发要点

1. 数据结构设计

  • 合理设计任务数据结构
  • 使用Map管理定时器
  • 状态同步更新

2. 状态管理

  • 任务状态转换
  • 活动任务计数
  • 进度更新控制

3. 界面优化

  • 清晰的任务展示
  • 直观的操作控制
  • 实时的状态反馈

六、注意事项

  1. 任务管理

    • 合理控制并发任务数量
    • 及时清理无用的定时器
    • 确保状态更新的准确性
  2. 性能考虑

    • 避免频繁的状态更新
    • 优化列表渲染
    • 合理使用计算属性
  3. 用户体验

    • 提供清晰的操作指引
    • 保持界面响应的及时性
    • 优化交互流程
Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐