温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

OpenHarmony ListView如何做动画

发布时间:2026-09-19 22:32:46 来源:亿速云 阅读:97 作者:小樊 栏目:软件技术

在 OpenHarmony(ArkUI) 中,ListView(API 9+ 一般用 List 组件)本身没有内建“列表项动画”属性,但可以通过 ArkUI 的动画能力 + 数据驱动 来实现常见动画效果。下面按常见场景给你讲做法和示例。


一、List 项进入 / 删除动画(最常用)

✅ 核心思路

  • 用 @State 管理列表数据
  • 使用 animateTo 或组件动画
  • 通过 @Animatable / animation 控制显隐和位移

示例:列表项添加时的淡入 + 位移动画

@Entry
@Component
struct ListAnimExample {
  @State listData: string[] = ['A', 'B', 'C']

  build() {
    Column() {
      Button('添加')
        .onClick(() => {
          animateTo({ duration: 300 }, () => {
            this.listData.push(`Item ${this.listData.length}`)
          })
        })

      List() {
        ForEach(this.listData, (item: string) => {
          ListItem() {
            Text(item)
              .fontSize(20)
              .padding(10)
          }
          .animation({ duration: 300 })
        }, (item: string) => item)
      }
    }
  }
}

✅ 效果:

  • 新增项会从默认位置淡入
  • 列表自动重排

二、删除项动画(推荐方式)

示例:删除时先动画再移除数据

removeItem(index: number) {
  animateTo({ duration: 300 }, () => {
    this.listData.splice(index, 1)
  })
}

配合:

ListItem()
  .animation({ duration: 300 })

三、Item 点击展开 / 折叠动画

示例:高度动画

@Component
struct ExpandItem {
  @State expanded: boolean = false

  build() {
    Column() {
      Text('点击展开')
        .onClick(() => {
          animateTo({ duration: 300 }, () => {
            this.expanded = !this.expanded
          })
        })

      if (this.expanded) {
        Text('详细信息')
          .height(50)
          .animation({ duration: 300 })
      }
    }
  }
}

四、Item 滑动出现动画(类似 iOS)

思路

  • 使用 translate
  • 初始 x: 100
  • onAppear 中归位
ListItem()
  .onAppear(() => {
    animateTo({ duration: 300 }, () => {
      this.offsetX = 0
    })
  })
  .translate({ x: this.offsetX })

五、官方推荐方式(API 10+)

✅ 使用 List + LazyForEach + animation ✅ 避免频繁 ForEach 全量刷新


六、常见坑提醒

❌ 不要在 ForEach 里用 index 作为 key
✅ 用唯一 id

ForEach(this.listData, item => item.id)

❌ 不要直接操作 DOM
✅ 一切通过 @State 驱动


七、如果你要的是“类似 RecyclerView 动画”

OpenHarmony 目前:

  • ✅ 支持基础动画
  • ❌ 没有 Android DiffUtil 自动动画
  • ✅ 需要手动 animateTo

八、总结

动画类型 实现方式
新增/删除 animateTo + ListItem.animation
展开 height + animateTo
滑动 translate + onAppear
复杂动画 custom animation

如果你告诉我:

  • OpenHarmony 版本(API 9 / 10 / 11)
  • 具体想要的动画(滑动删除?瀑布流?)

我可以直接给你可运行完整 Demo。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手