微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Jetpack Compose LazyColumn 对于已弃用,如何将 LazyColumn 与 listState 和对象列表一起使用?

如何解决Jetpack Compose LazyColumn 对于已弃用,如何将 LazyColumn 与 listState 和对象列表一起使用?

Jetpack Compose 1.0.0-alpha09 起,LazyColumnLazyColumnForIndexed 和行对应项已弃用。 LazyColumn 是如何使用的,在哪里、为什么以及我应该如何使用 rememberLazyListState

如果您能提供一个包含项目、状态和 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-beta06LazyColumn 会产生一个垂直滚动的列表。

类似于:

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。