鸿蒙Next 侧滑删除和长按拖拽排序

281 阅读1分钟

如图效果实现方式利用了LazyForEach 提供的拖拽交换能力 ,数据封装可以看这篇
鸿蒙Next--针对LazyForEach 做了个数据封装类

下面是实现过程:

@State arrayList: LazyDataSource<string> = new LazyDataSource()
//先构造假数据,实际项目由网络获取
aboutToAppear(): void {
  for (let index = 0; index < 99; index++) {
    this.arrayList.pushData("item:" + index)
  }
}

侧滑删除view

@Builder
itemEnd(index: number) {
  Text('删除')
    .width(80)
    .height('100%')
    .backgroundColor(Color.Red)
    .textAlign(TextAlign.Center)
    .onClick(() => {
      this.arrayList.deleteData(index)
    })
}

使用方法:

build() {
  Column() {
    List() {
      LazyForEach(this.arrayList, (item: string, index: number) => {
        ListItem() {
          Text(item).backgroundColor(Color.Pink)
            .width('100%').height('100%')
        }
        .margin(10)
        .height(100)
        .swipeAction({
          end: {
          //侧滑删除
            builder: this.itemEnd(index),
          }
        })

      }, (item: string, index: number) => JSON.stringify(item) + JSON.stringify(index))
          //拖拽排序能力
        .onMove((from: number, to: number) => {
          this.arrayList.moveDataWithoutNotify(from, to)
        })
    }.width('100%').height('100%').scrollBar(BarState.Off)
  }
}