Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add space between grid items in jetpack compose

I am currently trying to implement a gridview, it consists of 2 columns. I know i can implement my own grid view using columns and rows, but i just want to use existing approach although it is experimental.

@Composable
fun MyGridScreen() {
    LazyVerticalGrid(cells = GridCells.Fixed(2), modifier = Modifier.fillMaxSize(),contentPadding = PaddingValues(12.dp)) {
        items(15) {
            Box(
                contentAlignment = Alignment.Center,
                modifier = Modifier
                    .padding(10.dp)
                    .height(80.dp)
                    .background(Color.Red)
                    .aspectRatio(1f)

            ) {
                Text("Grid item $it", color = Color.White)
            }
        }
    }
} 

Below is the result i achieved. I can't put space below the item :(

enter image description here

like image 748
nesibeyyubov Avatar asked Sep 01 '25 05:09

nesibeyyubov


2 Answers

You need to set verticalArrangement and horizontalArrangement properties on the LazyVerticalGrid composable.

This will space the items by 10.dp in both the vertical and horizontal axis.

@Composable
fun MyGridScreen() {
    LazyVerticalGrid(
        cells = GridCells.Fixed(2),
        modifier = Modifier.fillMaxSize(),
        contentPadding = PaddingValues(12.dp),
        verticalArrangement = Arrangement.spacedBy(10.dp),
        horizontalArrangement = Arrangement.spacedBy(10.dp)
    ) {
        items(15) {
            Box(
                contentAlignment = Alignment.Center,
                modifier = Modifier
                    .padding(10.dp)
                    .height(80.dp)
                    .background(Color.Red)
                    .aspectRatio(1f)

            ) {
                Text("Grid item $it", color = Color.White)
            }
        }
    }
}
like image 157
Rafsanjani Avatar answered Sep 02 '25 19:09

Rafsanjani


Padding is exactly what you need in this case. But you need to understand that in compose modifiers order means a lot. By moving background modifier in between padding and sizes modifiers, you'll get what you need. And clickable ripple will work the same.

Check out more how modifiers order works: https://stackoverflow.com/a/65698101/3585796

.padding(10.dp)
.background(Color.Red)
.height(80.dp)
.aspectRatio(1f)

enter image description here

p.s. if you need your items to be a square, just put your box in one more box. Looks like width of items in LazyVerticalGrid gets overridden by the grid to fill max width, not sure if that's a bug or a feature.

like image 26
Philip Dukhov Avatar answered Sep 02 '25 18:09

Philip Dukhov