As of Jetpack Compose 1.0.0-alpha09
LazyColumn
, LazyColumnForIndexed
, and row counterparts are deprecated. How is LazyColumn
used, where, why, and how should i use rememberLazyListState
?
If you can provide a full example with items, state and onClick listener it would much obliged.
This documentation here describes how to use LazyColumn
instead of LazyColumnFor
.
https://developer.android.com/reference/kotlin/androidx/compose/foundation/lazy/package-summary#lazycolumn
Particular part of interest from the documentation:
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")
}
}
With 1.0.0-beta06
the LazyColumn
produces a vertically scrolling list.
Something like:
val itemsList = (0..30).toList()
LazyColumn {
items(itemsList) {
Text("Item is $it")
}
}
The LazyListState
is a state object that can be hoisted to control and observe scrolling. It is created via rememberLazyListState
.
val listState = rememberLazyListState()
It can be used to react and listen to scroll position and item layout changes.
// Provide it to LazyColumn
LazyColumn(state = liststate) {
// Check if the first visible item is past the first item
if (listState.firstVisibleItemIndex > 0){
//...
}
}
or to control the scroll 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")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With