鸿蒙开发List长按Item拖拽切换效果

发布于:2025-07-06 ⋅ 阅读:(14) ⋅ 点赞:(0)
鸿蒙开发List长按Item拖拽切换效果

android就很常见长按item拖来拖去切换,鸿蒙中也可以做,就是麻烦一点。

一、效果图:

在这里插入图片描述
这个看视频更直观点:

鸿蒙开发教程实战案例源码分享-List长按Item拖拽切换效果

二、思路:

自定义CardSortListItem组件,还有Image的gesture方法

三、关键代码:
@Entry
@ComponentV2
struct Index {
  @Local currentCardSort: Array<number> = []

  aboutToAppear(): void {
    this.currentCardSort = Constants.DEFAULT_CARD_SORT
  }

  build() {
    Column() {
      Text("长按item拖拽切换不同位置item")
        .fontSize(24)
        .fontWeight(FontWeight.Bold)
        .margin({
          top:100
        })
      Stack() {
        this.cardSortList()
      }
      .width('100%')
      .layoutWeight(1)
      .margin({
        top:16
      })
    }
    .height('100%')
    .width('100%')
  }

  @Builder
  cardSortList() {
    List() {
      ForEach(this.currentCardSort, (item: number) => {
        CardSortListItem({
          weatherCardItemType: item,
          index: this.currentCardSort.findIndex(it => it == item),
          length: this.currentCardSort.length,
          onReorderStart: () => {

            return true
          },
          onChangeItem: (from, to) => {
            if (ArrayUtil.isNotEmpty(this.currentCardSort)) {
              const tmp = this.currentCardSort.splice(from, 1)
              this.currentCardSort.splice(to, 0, tmp[0])
            }
          },
          onReorderDone: () => {

          },
          onWeatherObserveSortTap: () => {

          }
        })
      }, (item: number) => item.toString())
    }
    .width('100%')
    .height('100%')
    .divider({ strokeWidth: 12, color: $r('app.color.transparent') })

  }
}
四、项目demo源码结构图:

在这里插入图片描述

有需要完整demo源码的私信我,我每天都看私信的