Jetpack Compose中RecyclerView
或ListView
的等效组件为LazyColumn
(垂直列表)和LazyRow
(水平列表).它们仅构成和布置当前可见的项目.
您可以使用它,方法是将数据格式化为列表,并将其与@Composable
回调一起传递,该回调将发出列表中给定项的UI.例如:
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!")
}
}
还有索引变体,除了项目本身之外,还提供集合中的索引:
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
.