Jetpack Compose LazyColumnFor 已弃用,如何将 LazyColumn 与 listState 和对象列表一起使用?
Jetpack Compose LazyColumnFor deprecated, how to use LazyColumn with listState and list of objects?
自 Jetpack Compose 1.0.0-alpha09
LazyColumn
、LazyColumnForIndexed
起,行对应项已弃用。 LazyColumn
是如何使用的,我应该在哪里、为什么以及如何使用 rememberLazyListState
?
如果您能提供包含项目、状态和 onClick 侦听器的完整示例,我们将非常感激。
此处的文档描述了如何使用 LazyColumn
而不是 LazyColumnFor
。
文档中感兴趣的特定部分:
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.Text
val itemsList = (0..5).toList()
val itemsIndexedList = listOf("A", "B", "C")
LazyColumn {
items(itemsList) {
Text("Item is $it")
}
item {
Text("Single item")
}
itemsIndexed(itemsIndexedList) { index, item ->
Text("Item at index $index is $item")
}
}
对于 1.0.0-beta06
,LazyColumn
生成垂直滚动列表。
类似于:
val itemsList = (0..30).toList()
LazyColumn {
items(itemsList) {
Text("Item is $it")
}
}
LazyListState
是一个状态对象,可以吊起来控制和观察滚动。它是通过 rememberLazyListState
.
创建的
val listState = rememberLazyListState()
可用于响应和监听滚动位置和项目布局变化。
// Provide it to LazyColumn
LazyColumn(state = liststate) {
// Check if the first visible item is past the first item
if (listState.firstVisibleItemIndex > 0){
//...
}
}
或者控制滚动位置:
// Remember a CoroutineScope to be able to launch
val coroutineScope = rememberCoroutineScope()
LazyColumn(state = listState) {
// ...
}
lazyListState.animateScrollToItem(lazyListState.firstVisibleItemIndex)
Button (
onClick = {
coroutineScope.launch {
// Animate scroll to item with index=5
listState.animateScrollToItem(index = 5)
}
}
){
Text("Click")
}
自 Jetpack Compose 1.0.0-alpha09
LazyColumn
、LazyColumnForIndexed
起,行对应项已弃用。 LazyColumn
是如何使用的,我应该在哪里、为什么以及如何使用 rememberLazyListState
?
如果您能提供包含项目、状态和 onClick 侦听器的完整示例,我们将非常感激。
此处的文档描述了如何使用 LazyColumn
而不是 LazyColumnFor
。
文档中感兴趣的特定部分:
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.Text
val itemsList = (0..5).toList()
val itemsIndexedList = listOf("A", "B", "C")
LazyColumn {
items(itemsList) {
Text("Item is $it")
}
item {
Text("Single item")
}
itemsIndexed(itemsIndexedList) { index, item ->
Text("Item at index $index is $item")
}
}
对于 1.0.0-beta06
,LazyColumn
生成垂直滚动列表。
类似于:
val itemsList = (0..30).toList()
LazyColumn {
items(itemsList) {
Text("Item is $it")
}
}
LazyListState
是一个状态对象,可以吊起来控制和观察滚动。它是通过 rememberLazyListState
.
val listState = rememberLazyListState()
可用于响应和监听滚动位置和项目布局变化。
// Provide it to LazyColumn
LazyColumn(state = liststate) {
// Check if the first visible item is past the first item
if (listState.firstVisibleItemIndex > 0){
//...
}
}
或者控制滚动位置:
// Remember a CoroutineScope to be able to launch
val coroutineScope = rememberCoroutineScope()
LazyColumn(state = listState) {
// ...
}
lazyListState.animateScrollToItem(lazyListState.firstVisibleItemIndex)
Button (
onClick = {
coroutineScope.launch {
// Animate scroll to item with index=5
listState.animateScrollToItem(index = 5)
}
}
){
Text("Click")
}