【问题标题】:Jetpack Compose LazyColumnFor deprecated, how to use LazyColumn with listState and list of objects?Jetpack Compose LazyColumnFor 已弃用,如何将 LazyColumn 与 listState 和对象列表一起使用?
【发布时间】:2020-12-22 20:15:12
【问题描述】:

从Jetpack Compose 1.0.0-alpha09 LazyColumn、LazyColumnForIndexed 开始,不推荐使用行对应项。 LazyColumn 是如何使用的,在哪里、为什么以及如何使用 rememberLazyListState?

如果你能提供一个包含项目、状态和 onClick 监听器的完整示例,那将非常有帮助。

【问题讨论】:

    标签: android android-jetpack-compose android-jetpack-compose-list


    【解决方案1】:

    此处的此文档描述了如何使用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")
        }
    }
    

    【讨论】:

    • 谢谢。你介意展示如何使用rememberLazyListState 吗?是用来保存和恢复滚动位置的吗?
    • 我猜这和其他remembers 一样。您将滚动位置保留在 Composable 函数中,对吗?
    • 需要导入import androidx.compose.foundation.lazy.items
    【解决方案2】:

    使用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")
    }
    

    【讨论】:

      猜你喜欢
      • 2022-07-29
      • 1970-01-01
      • 2020-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 2022-11-10
      • 2022-11-05
      相关资源
      最近更新 更多