Column : All of the item in the list is composed.
LazyList : Only composes those on the screen.
A vertical lazy list.
LazyColumn {
item {
Text(text = "First item")
}
items(data) { item ->
Text(text = "Item: $item")
}
itemsIndexed(data) { index, item ->
Text(text = "Item: $index $item")
}
item {
Text(text = "Last item")
}
}
item
: Adds single itme to the list.
items
: Adds multiple items.
itemsIndexed
: Adds multiple items with index.
contentPadding = PaddingValue
: Padding without content clipping.
horizontalArrangement = Arrangement
: Space between list items.
rememberLazyListState
State for lazy list. Holds scroll positions and informations about the list. Also provides useful functions like scrolling to positions.
val state = rememberLazyListState()
val enableScrollToTop by remember {
derivedStateOf {
state.firstVisibleItemIndex > 0
}
}
derivedStateOf
: Only updates when the derived state is changed.
Lazy list with grid layout.
LazyVerticalGrid(
columns = GridCells.Adaptive(minSize = 128.dp)
//columns = GridCells.Fixed(3)
) {
items(photos) { photo ->
PhotoItem(photo)
}
}
GridCells.Adaptive
Measures number of cells with given minimum size of cells and screen size. it's determined by screen size divided by minimum item size. Extra spaces are distributed among items evenly.
For example, screen width of 300dp will hold two columns of item with 150dp being their width.
GridCells.Fixed
Defines the grid with given column size. Item size will be that of screen size divided by column size.
Lazy list with staggered items.
LazyVerticalStaggeredGrid(
columns = StaggeredGridCells.Adaptive(200.dp),
verticalItemSpacing = 4.dp,
horizontalArrangement = Arrangement.spacedBy(4.dp),
content = {
items(randomSizedPhotos) { photo ->
AsyncImage(
model = photo,
contentScale = ContentScale.Crop,
contentDescription = null,
modifier = Modifier.fillMaxWidth().wrapContentHeight()
)
}
},
modifier = Modifier.fillMaxSize()
)
LazyVerticalStaggeredGrid(
columns = StaggeredGridCells.Fixed(3),
verticalItemSpacing = 4.dp,
horizontalArrangement = Arrangement.spacedBy(4.dp),
content = {
items(randomSizedPhotos) { photo ->
AsyncImage(
model = photo,
contentScale = ContentScale.Crop,
contentDescription = null,
modifier = Modifier.fillMaxWidth().wrapContentHeight()
)
}
},
modifier = Modifier.fillMaxSize()
)
Things to keep in mind
Give default size to list items
List items with 0dp will cause LazyList to compose all of the item before items have size. These composables are redundant since most of them will be removed when some of the items gets proper size in the list and pushes out other list itmes.
Keep one element in one item
In
item
scope, multiple elements can fit but has some drawbacks. Item is composed as a whole, so part of an item showing on the screen will cause all of the elements to be composed. This violates the principles of lazy list.
Reference
https://www.youtube.com/watch?v=1ANt65eoNhQ
https://developer.android.com/develop/ui/compose/lists#lazy