Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grid Layout with equally height rows in Jetpack Compose

Jetpack Compose:

I want to create a grid layout like UI with equally height rows, but I can't find a function for getting the current usable screen size (The application should look like that)

How the result should look like:

Have a look at the link mentioned above

What I have tried:

I tried to use Modifier.fillMaxHeight() inside of LazyVerticalGrid for generating equally sized rows, but it didn't work. Beside of that, I also had the idea of setting the height manually for every row item, but I couldn't find a function for getting the usable screen size in jetpack compose (I then would have divided the screen height by the number of rows).

val numbers = (0..34).toList()

LazyVerticalGrid(
    cells = GridCells.Fixed(7)

) {
    items(numbers.count()) {
        Column(horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Text(text = "#"+numbers.get(it))
        }
    }
}
like image 571
Dev2021 Avatar asked Dec 04 '25 16:12

Dev2021


1 Answers

You can use the aspectRatio modifier:

LazyVerticalGrid(
    columns = GridCells.Adaptive(100.dp),
) {
    items(100) {
        Box(
            modifier = Modifier.aspectRatio(1f)
        ) { }
    }
}

Full example:

enter image description here


@Composable
fun Body(modifier: Modifier) {
    Column (
        modifier = modifier,
    ) {
        Text(
            text = "Without aspect ratio",
            modifier = Modifier.padding(12.dp),
            style = MaterialTheme.typography.h5,
        )
        LazyVerticalGrid(
            columns = GridCells.Adaptive(100.dp),
            modifier = Modifier.weight(1f),
        ) {
            items(100) {
                Surface (
                    modifier = Modifier
                        .padding(12.dp),
                    color = Color(0xff2187bb),
                ) {
                    RandomSizeBox()
                }
            }
        }
        Divider()
        Text(
            "With aspect ratio",
            modifier = Modifier.padding(12.dp),
            style = MaterialTheme.typography.h5,
        )
        LazyVerticalGrid(
            columns = GridCells.Adaptive(100.dp),
            modifier = Modifier.weight(1f),
        ) {
            items(100) {
                Surface (
                    modifier = Modifier
                        .aspectRatio(1f)
                        .padding(12.dp),
                    color = Color(0xffbb2187),
                ) {
                    RandomSizeBox()
                }
            }
        }
    }
}

@Composable
fun RandomSizeBox() {
    Box(modifier = Modifier.height((10 + Math.random() * 90).dp))
}

like image 166
Raed Mughaus Avatar answered Dec 06 '25 19:12

Raed Mughaus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!