#鸿蒙通关秘籍#HarmonyOS中如何使用ListItem的选中状态?

HarmonyOS
2024-12-04 14:23:17
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
SCM风诗

在HarmonyOS中,可以通过ListItem的selected属性设置或获取选中状态,并借助事件onSelect处理状态变化,如下:

@Entry
@Component
struct SelectableListExample {
  @State selectedItem: number = -1

  build() {
    Column() {
      List({ space: 10 }) {
        ForEach([0, 1, 2, 3], (item: number) => {
          ListItem() {
            Text('Item ' + item)
              .width('100%')
              .height(50)
              .fontSize(16)
              .textAlign(TextAlign.Center)
          }
          .selected(this.selectedItem === item)
          .onSelect((isSelected: boolean) => {
            if (isSelected) {
              this.selectedItem = item
            }
          })
        })
      }
    }
    .padding(10)
    .backgroundColor(0xFFFFFF)
    .width('100%')
    .height('100%')
  }
}
  • 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.

在该示例中,selectedItem用来存储当前选中的ListItem索引,通过onSelect事件在选中状态改变时更新选择。

分享
微博
QQ
微信
回复
2024-12-04 15:10:27
相关问题