#鸿蒙通关秘籍#如何在HarmonyOS中利用ListItem实现滑动删除?

HarmonyOS
2024-12-04 13:03:10
1079浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
hm67482cb63a365

为了在HarmonyOS中实现滑动删除功能,可以利用ListItem的swipeAction属性来配置滑动操作项,如下:

// 使用ArkTS编写示例
@Entry
@Component
struct SwipeDeleteExample {
  @State arr: Array<number> = [0, 1, 2, 3, 4]
  
  @Builder itemEnd() {
    Row() {
      Button("删除")
        .margin("4vp")
        .onClick(() => {
          // 删除操作
        })
    }
    .padding("8vp")
    .justifyContent(FlexAlign.Center)
  }

  build() {
    Column() {
      List({ space: 10 }) {
        ForEach(this.arr, (item: number) => {
          ListItem() {
            Text('Item ' + item)
              .width('100%')
              .height(100)
              .fontSize(20)
              .textAlign(TextAlign.Center)
              .onClick(() => {
                // 点击事件
              })
          }
          .swipeAction({
            end: {
              builder: () => this.itemEnd(),
              onAction: () => {
                this.arr = this.arr.filter(val => val !== item)
              },
              actionAreaDistance: 60
            }
          })
        }, item => item)
      }
    }
    .width('100%')
    .padding(10)
    .backgroundColor(0xF5F5F5)
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.

在这个示例中,通过配置swipeActionend属性,实现了在向左滑动时出现删除按钮,并在点击时从数组中移除元素。

分享
微博
QQ
微信
回复
2024-12-04 15:58:02


相关问题