20

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

nasibeyyubov
  • 1,735
  • 3
  • 11
  • 28

2 Answers2

51

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)
            }
        }
    }
} 
Rafsanjani
  • 4,352
  • 1
  • 14
  • 21
3

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.

Phil Dukhov
  • 67,741
  • 15
  • 184
  • 220