![]() |
VOOZH | about |
In Jetpack compose we have Composables like Column and Row but when the app needs to display a large number of items in a row or columns then it's not efficient if done by Row or Column Composable. Therefore we have Lazy Composables in Jetpack Compose. Mainly we have three kinds of Lazy Composables Row, Column, and Grid. In this article, we are going to look at all three Lazy Composables. We will build a simple app that demonstrates all three composables in action.
Prerequisites
Below is the step-by-step implementation of the Lazy Row, Lazy Column and Lazy Grid.
To create a new project in the Android Studio, please refer to How to Create a new Project in Android Studio with Jetpack Compose.
Note: Select Kotlin as the programming language.
Below is the File Structure of the Application:
Open MainActivity.kt and create two Composables, one for Row Item and One for Column Item
Unlike Column or Row Composable we cannot place composable inside directly inside Lazy Composables. Lazy Composables provides functions to place items in the Lazy Scope. There is mainly five overloaded functions.
1. Places one item in the Lazy Scope
item {
RowItem(number = 0)
}
2. Places count items in the Lazy Scope
items (count = 10) {currentCount->
RowItem(number = currentCount)
}
3. Places number of items present same as the size of Array
val number: Array<Int>
items (numbers) {arrayItem->
RowItem(number = arrayItem)
}
4. Places number of items present same as the size of Array, and provides item(in list) and index of current Item.
val number: Array<Int>
itemsIndexed (numbers) { index: Int, item: Int ->
RowItem(number = index)
}
Create a Composable in MainActivity.kt, here we will place Lazy row to demonstrate Lazy Row
Output:
Create a Composable in MainActivity.kt, here we will place Lazy Column to demonstrate Lazy Column
Output:
Create a Composable in MainActivity.kt, here we will place LazyVerticalGrid. It's almost the same as other lazy composable but it takes an extra parameter cells which is the number of grid items in one row / minimum width of one item. cells can be either GridCells.Fixed(count), It fixes the items displayed in one grid row. Another value it accepts is GridCells.Adaptive(minWidth), it sets the minWidth of each grid item.
Output:
Navigate to app > kotlin+java > {package-name} > MainActivity.kt and paste the following code.
MainActivity.kt: