Lazy Composables in Android Jetpack Compose – Columns, Rows, Grids
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.
- Knowledge of Kotlin.
- Knowledge of Jetpack Compose.
Step by Step Implementation
Step 1: Create a New Project (Or use it in the existing Compose project)
To create a new project in the Android Studio Canary version, refer to the article How to Create a new Project in the Android Studio Canary Version with Jetpack Compose.
Step 2 : Add Color (optional)
Open ui > theme > Colors.kt and add
val GreenGfg = Color(0xFF0F9D58)
Step 3: Create Row and Column Items that are going to be displayed
Open MainActivity.kt and create two Composables, one for Row Item and One for Column Item
Step 4: Working with Lazy Composables
Unline Column or Row Composable we cannot place composable inside directly inside Lazy Composables. Lazy Composables provides functions to place items in the LazyScope. There is mainly five overloaded functions.
|item||Composable||Places one item in the LazyScope|
|items||count,key(optional),Composable||Places count items in the LazyScope|
|items||List, Composable||Places number of items present same as the size of List,|
|items||Array, Composable||Places number of items present same as the size of Array,|
Places number of items present same as the size of Array,
and provides item(in list) and index of current Item.
Step 4.1: Lazy Row
Create a Composable in MainActivity.kt, here we will place Lazy row to demonstrate Lazy Row
Step 4.2: Lazy Column
Create a Composable in MainActivity.kt, here we will place Lazy Column to demonstrate Lazy Column
Step 4.3: Lazy Grid
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.
Step 5: Placing the Composables on Screen
Now place all three examples in setContentView in MainActivity Class.
Note: Before running this whole code, make sure to do Step 2, or replace GreenGfg with your own color.
Now run the app on an emulator or phone.
Get the complete code from GitHub.
Please Login to comment...