In Jetpack Compose, GridView
from the traditional View system is replaced by LazyVerticalGrid, which is part of the Accompanist library or Jetpack Compose’s LazyLayout
system.
Basic Example of LazyVerticalGrid
Here’s how to use LazyVerticalGrid
for creating grid layouts:
Dependency for LazyVerticalGrid (if not part of core library yet)
Make sure you include the latest Compose library version in your build.gradle
file.
implementation "androidx.compose.foundation:foundation:<latest_version>"
Using LazyVerticalGrid
Here’s a basic example:
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.text.BasicText
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
@Composable
fun SimpleGridView() {
val itemsList = List(20) { "Item $it" } // Example list
LazyVerticalGrid(
columns = GridCells.Fixed(2), // Defines a fixed number of columns
modifier = Modifier.padding(16.dp)
) {
items(itemsList.size) { index ->
BasicText(
text = itemsList[index],
style = MaterialTheme.typography.bodyMedium,
modifier = Modifier.padding(8.dp)
)
}
}
}
Types of Grid Cells
You can customize the grid layout using the GridCells
parameter:
GridCells.Fixed(n: Int)
Specifies a fixed number of columns. Example:GridCells.Fixed(3)
creates 3 columns.GridCells.Adaptive(minSize: Dp)
Dynamically adjusts the number of columns based on the available space, ensuring each cell is at least the givenminSize
. Example:
LazyVerticalGrid(
columns = GridCells.Adaptive(minSize = 100.dp)
) {
// Content
}
Customizing Items
You can fully customize each grid item using composables.
@Composable
fun CustomGridView() {
val itemsList = List(20) { "Item $it" }
LazyVerticalGrid(
columns = GridCells.Fixed(2),
modifier = Modifier.padding(16.dp)
) {
items(itemsList.size) { index ->
Box(
modifier = Modifier
.padding(8.dp)
.background(MaterialTheme.colorScheme.primary)
.fillMaxSize()
) {
Text(
text = itemsList[index],
color = Color.White,
modifier = Modifier.align(Alignment.Center)
)
}
}
}
}
Key Features of LazyVerticalGrid
- Laziness: Like
LazyColumn
, it only composes visible items. - Customizable Layouts: Fully customizable grid items and spacing.
- Adaptive Columns: Automatically adjusts the number of columns based on screen width with
GridCells.Adaptive
. - Performance: Efficient memory usage and UI updates, suitable for large grids.
Handling Large Data Sets
For large datasets, you can combine LazyVerticalGrid
with Paging 3 library for smooth scrolling and on-demand loading.
LazyVerticalGrid is a powerful replacement for GridView
, offering modern and flexible grid layouts in Jetpack Compose.