Android Compose Grid layout

Eang Tithsophorn
2 min readApr 4, 2023

--

Hello , My name is Eang Tithsophorn. I had been working with mobile development more than 3 years. I will share with my knowledge for you guys.

For Grid layout we have two layout that provide by android compose itself:

  • LazyVerticalGrid
  • LazyHorizontalGrid

The list of Usage:

  • LazyVerticalGrid
  • Material3

You can find more here

Note : Grid layout it kinda need height . As example for you to try , If you have LazyVerticalGrid inside of LazyColumn it will crash when run the app. I believe if you give it height it would be just fine.

LazyVerticalGrid(
columns = GridCells.Fixed(3),
)

It mean that you have columns of 3 and for display the cell of item.

@Composable
fun LazyVerticalGridView() {
val data = listOf(
Icons.Default.Send,
Icons.Default.Wallet,
Icons.Default.Payments,
Icons.Default.PhoneCallback,
Icons.Default.Savings,
Icons.Default.Calculate
)
LazyVerticalGrid(columns = GridCells.Fixed(3)) {
items(data) { item ->
Card(
modifier = Modifier
.padding(4.dp)
.height((UIApplication.height() * 0.1).dp)
.clickable {

},
colors = CardDefaults.elevatedCardColors(containerColor = Color.White),
elevation = CardDefaults.elevatedCardElevation(defaultElevation = 3.dp),
) {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.fillMaxSize()
) {
Icon(imageVector = item, contentDescription = "image for category")
}
}
}
}
}

For result

Congrats!

If you want to add title section on the top items list

you can add by this:

LazyVerticalGrid(columns = GridCells.Fixed(3)) {
item {
Text(text = "LazyVerticalGridView")
}
.......
items(data) { item ->
.......
}
}

The result will be

Opppps it doest look like what you want right?

Here my explain for you , since you fix the columns side to be 3. so item will be follow the same rules.

The solution for you.

LazyVerticalGrid(columns = GridCells.Fixed(3)) {
item (span = { GridItemSpan(3) }) {
Text(text = "LazyVerticalGridView")
}
.......
items(data) { item ->
.......
}
}
Problem solve!

But it kinda hard for repeated for give GridItemSpan everytime.

item (span =  { GridItemSpan(3) })

move to extension function

fun LazyGridScope.itemCell(
content: @Composable LazyGridItemScope.() -> Unit
) {
item(span = { GridItemSpan(this.maxLineSpan) }, content = content)
}

when trigger it.

itemCell {
Text(text = "LazyVerticalGridView")
}

That’s it for LazyGrid.

Thanks you for checkout.

--

--

Eang Tithsophorn
Eang Tithsophorn

Written by Eang Tithsophorn

I am Mobile Development Learner. My mobile list box has Android , iOS and Flutter. More information http://128.199.87.161/

No responses yet