HarmonyOS 5.0.0 或以上:实现圆形加载进度动效与状态切换展示


一、功能简介

本篇将实现一个圆形加载进度动效,并结合状态切换展示不同的加载状态,如“加载中 → 加载成功/失败”,适用于上传、下载、处理等耗时场景中的视觉反馈优化。


二、关键技术点

功能 技术实现
圆形进度动画 Progress({value}) + 动态状态控制
状态切换 @State status 控制加载中/成功/失败展示
自动结束动画 setTimeout() 模拟处理结束后状态变更
补充动效 使用 scale/opacity 添加状态切换过渡

三、页面结构

entry/src/main/ets/pages/CircleProgressDemo.ets

四、ArkTS 实战代码(CircleProgressDemo.ets)

@Entry
@Component
struct CircleProgressDemo {
  @State progress: number = 0
  @State status: 'idle' | 'loading' | 'success' | 'fail' = 'idle'

  startLoading() {
    this.status = 'loading'
    this.progress = 0

    const interval = setInterval(() => {
      this.progress += 5
      if (this.progress >= 100) {
        clearInterval(interval)
        setTimeout(() => {
          this.status = Math.random() > 0.5 ? 'success' : 'fail'
        }, 300)
      }
    }, 60)
  }

  getStatusText(): string {
    switch (this.status) {
      case 'loading': return '加载中...'
      case 'success': return '✅ 加载成功'
      case 'fail': return '❌ 加载失败'
      default: return ''
    }
  }

  build() {
    Column() {
      Text('HarmonyOS 5.0.0 或以上')
        .fontSize(20)
        .margin({ bottom: 20 })

      If(this.status === 'loading', () => {
        Progress({ value: this.progress / 100 })
          .type(ProgressType.Circle)
          .width(120).height(120)
          .strokeWidth(8)
          .color('#007DFF')
          .backgroundColor('#e0e0e0')
          .margin({ bottom: 12 })
          .animate({ duration: 100 })
      }, () => {
        If(this.status === 'success', () => {
          Text('')
            .fontSize(60)
            .scale({ x: 1.2, y: 1.2 })
            .opacity(1)
            .animate({ duration: 300 })
        }, () => {
          If(this.status === 'fail', () => {
            Text('')
              .fontSize(60)
              .rotate({ angle: 10 })
              .animate({ duration: 200 })
          })
        })
      })

      Text(this.getStatusText())
        .fontSize(16)
        .margin({ bottom: 20 })

      Button(' 启动加载')
        .onClick(() => this.startLoading())
    }
    .width('100%')
    .height('100%')
    .alignItems(HorizontalAlign.Center)
    .justifyContent(FlexAlign.Center)
    .backgroundColor('#f5f5f5')
  }
}

五、运行效果说明

  • 点击按钮后加载动画启动;

  • 圆形进度条旋转至 100%,约 1.2 秒;

  • 自动进入“加载成功”或“失败”状态;

  • 成功展示 动效,失败展示 表情+震动。


六、常见问题与优化建议

问题 表现 原因 建议
进度条卡顿 步长或延迟设置不合理 建议步长控制在 25,间隔 4060ms 更顺畅
状态切换突兀 没有过渡动画 使用 .scale() / .opacity() / .rotate() 配合 .animate()
多次点击错误 多状态并发 加锁或判断 status 是否为 idle 再开始新加载

七、拓展建议

  • 加入 retry 逻辑,失败后可重试;

  • 提供自定义颜色和图标配置;

  • 与文件上传、数据处理任务等联动;

  • 可封装为 通用组件;

  • 引入旋转 loading 图标替代 Progress,更有品牌识别度。


下一篇为第13篇:

《HarmonyOS 5.0.0 或以上:实现弹性拖拽卡片动效与归位缓动反馈》

你可能感兴趣的:(鸿蒙,x,AI,产品实战,harmonyos,pytorch,华为)