Jetpack Compose 相当于 RecyclerView 或 ListView 是什么? [英] What is the Jetpack Compose equivalent of RecyclerView or ListView?
问题描述
在 Jetpack Compose 中,如何在仅布置可见项目的同时显示大数据列表,而不是在初始布局过程中组合和布置每个项目?这将类似于 View
工具包中的 RecyclerView
和 ListView
.
In Jetpack Compose, how can I display a large list of data while laying out only the visible items, instead of composing and laying out every item on the initial layout pass? This would be similar to RecyclerView
and ListView
in the View
toolkit.
可以使用 for
循环将 Column
内的所有组件放置在 VerticalScroller
中,但这会导致丢弃框架和在大量项目上的性能不佳.
One could use a for
loop to place all of the components inside of a Column
in a VerticalScroller
, but this would result in dropped frames and poor performance on larger numbers of items.
注意:这是一个规范的自我回答问题,以抢先/处理类似的问题
推荐答案
Jetpack Compose 中 RecyclerView
或 ListView
的等效组件是 LazyColumn
用于垂直列表和 LazyRow
用于一个水平列表.它们仅构成和布置当前可见的项目.
The equivalent component to RecyclerView
or ListView
in Jetpack Compose is LazyColumn
for a vertical list and LazyRow
for a horizontal list. These compose and lay out only the currently visible items.
您可以通过将数据格式化为列表并使用 @Composable
回调传递它来使用它,该回调为列表中的给定项目发出 UI.例如:
You can use it by formatting your data as a list and passing it with a @Composable
callback that emits the UI for a given item in the list. For example:
val myData = listOf("Hello,", "world!")
LazyColumn {
items(myData) { item ->
Text(text = item)
}
}
val myData = listOf("Hello,", "world!")
LazyRow {
items(myData) { item ->
Text(text = item)
}
}
您也可以一次指定单个项目:
You can also specify individual items one at a time:
LazyColumn {
item {
Text("Hello,")
}
item {
Text("world!")
}
}
LazyRow {
item {
Text("Hello,")
}
item {
Text("world!")
}
}
还有索引变体,除了提供项目本身之外,还提供集合中的索引:
There are also indexed variants, which provide the index in the collection in addition to the item itself:
val myData = listOf("Hello,", "world!")
LazyColumn {
itemsIndexed(myData) { index, item ->
Text(text = "Item #$index is $item")
}
}
val myData = listOf("Hello,", "world!")
LazyRow {
itemsIndexed(myData) { index, item ->
Text(text = "Item #$index is $item")
}
}
在以前的版本中,这些 API 被称为 AdapterList
、LazyColumnItems
/LazyRowItems
和 LazyColumnFor
/LazyRowFor
.
These APIs were, in previous releases, known as AdapterList
, LazyColumnItems
/LazyRowItems
, and LazyColumnFor
/LazyRowFor
.
这篇关于Jetpack Compose 相当于 RecyclerView 或 ListView 是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!