繁体   English   中英

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 LazyColumnLazyColumnForIndexed 、 LazyColumnForIndexed 和 row 对应项已弃用。 LazyColumn是如何使用的,在哪里,为什么,以及我应该如何使用rememberLazyListState

如果您可以提供完整的项目示例,state 和 onClick 侦听器将非常感激。

此处的此文档描述了如何使用LazyColumn而不是LazyColumnFor

https://developer.android.com/reference/kotlin/androidx/compose/foundation/lazy/package-summary#lazycolumn

文档中特别感兴趣的部分:

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是一个 state object 可以被提升来控制和观察滚动。 它是通过rememberLazyListState创建的。

val listState = rememberLazyListState()

它可以用来反应和收听滚动 position 和项目布局变化。

// Provide it to LazyColumn
LazyColumn(state = liststate) {
    // Check if the first visible item is past the first item
   if (listState.firstVisibleItemIndex > 0){
       //...
   }
}

或控制滚动 position:

// 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")
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM