温馨提示×

温馨提示×

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

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

OpenHarmony ListView怎么绑定数据

发布时间:2026-09-20 00:12:47 来源:亿速云 阅读:97 作者:小樊 栏目:软件技术

在 OpenHarmony(ArkUI) 中,并没有传统 Android 里的 ListView 组件,而是使用 List + ForEach / LazyForEach 来实现列表并绑定数据。下面给你几种常见写法。


一、最基础的 List 数据绑定(ForEach)

1️⃣ 定义数据

interface Item {
  id: number
  name: string
}

@Entry
@Component
struct ListViewPage {
  private data: Item[] = [
    { id: 1, name: '苹果' },
    { id: 2, name: '香蕉' },
    { id: 3, name: '橙子' }
  ]

  build() {
    List() {
      ForEach(this.data, (item: Item) => {
        ListItem() {
          Text(item.name)
            .fontSize(20)
            .padding(10)
        }
      }, (item: Item) => item.id.toString())
    }
  }
}

✅ 适合 数据量小、固定 的列表


二、动态数据绑定(@State)

@Entry
@Component
struct ListViewPage {
  @State data: Item[] = []

  aboutToAppear() {
    this.data = [
      { id: 1, name: '语文' },
      { id: 2, name: '数学' }
    ]
  }

  build() {
    List() {
      ForEach(this.data, (item: Item) => {
        ListItem() {
          Text(item.name)
        }
      }, (item: Item) => item.id.toString())
    }
  }
}

✅ 数据变化会自动刷新 UI


三、长列表性能优化(LazyForEach)

当数据 很多(上百/上千) 时使用 LazyForEach

1️⃣ 实现 DataSource

class MyDataSource implements IDataSource {
  private list: Item[]

  constructor(list: Item[]) {
    this.list = list
  }

  totalCount(): number {
    return this.list.length
  }

  getData(index: number): Item {
    return this.list[index]
  }

  registerDataChangeListener() {}
  unregisterDataChangeListener() {}
}

2️⃣ 使用 LazyForEach

@Entry
@Component
struct ListViewPage {
  private dataSource = new MyDataSource([
    { id: 1, name: 'A' },
    { id: 2, name: 'B' }
  ])

  build() {
    List() {
      LazyForEach(this.dataSource, (item: Item) => {
        ListItem() {
          Text(item.name)
        }
      }, (item: Item) => item.id.toString())
    }
  }
}

✅ 官方推荐用于 高性能列表


四、点击事件绑定

ListItem() {
  Text(item.name)
}
.onClick(() => {
  console.log('点击了:' + item.name)
})

五、常见误区

❌ OpenHarmony 没有 ListView.setAdapter()
✅ 使用 List + ForEach / LazyForEach


如果你愿意,我可以:

  • 给你一个 完整 Demo 工程
  • 讲 List 和 Grid 的区别
  • 讲 如何下拉刷新 / 上拉加载

你现在是 OpenHarmony 3.x 还是 4.x?

向AI问一下细节

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

AI
助
手