4. List and Grid in Compose
🎯 Goal : In this article, we will explore how to create lists and grids in Jetpack Compose, covering LazyColumn for vertical lists, LazyRow for horizontal lists, and LazyGrid for grid-based layouts.
Jetpack Compose provides LazyColumn, LazyRow, and LazyGrid for creating efficient and scrollable lists and grids. These composables only render visible items, making them performance-friendly for large data sets.
LazyColumn (Vertical List)
LazyColumn is used for scrollable vertical lists, similar to RecyclerView in XML-based UIs.
@Composable
fun VerticalListExample() {
LazyColumn {
items(10) { index ->
Text(
text = "Item #$index",
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
)
}
}
}
✅ Dynamically creates 10 list items
✅ Only visible items are rendered (performance-optimized)
LazyRow (Horizontal List)
LazyRow is used for horizontal scrolling lists.
@Composable
fun HorizontalListExample() {
LazyRow {
items(10) { index ->
Text(
text = "Item #$index",
modifier = Modifier
.padding(16.dp)
.background(Color.Gray)
)
}
}
}
✅ Items scroll horizontally instead of vertically
LazyVerticalGrid (Grid Layout)
For grid-based layouts, use LazyVerticalGrid.
📌 Step 1: Add Dependency (if using Compose < 1.2)
implementation("androidx.compose.foundation:foundation:1.4.0")
@Composable
fun GridExample() {
LazyVerticalGrid(columns = GridCells.Fixed(2)) { // 2 columns
items(10) { index ->
Text(
text = "Item #$index",
modifier = Modifier
.padding(16.dp)
.background(Color.LightGray)
.padding(16.dp)
)
}
}
}
✅ Creates a grid with 2 columns
✅ GridCells.Fixed(2) → Defines a fixed column count
Grid with Adaptive Column Width
Instead of a fixed number of columns, you can use adaptive columns based on available space.
@Composable
fun AdaptiveGridExample() {
LazyVerticalGrid(columns = GridCells.Adaptive(minSize = 100.dp)) {
items(10) { index ->
Text(
text = "Item #$index",
modifier = Modifier
.padding(8.dp)
.background(Color.Cyan)
.padding(16.dp)
)
}
}
}
✅ GridCells.Adaptive(100.dp) → Adjusts columns dynamically based on screen size
⭐ Next Up: Managing State in Jetpack Compose
🔎 Click “Learn Jetpack Compose in 30 Days” to see all articles
