Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center vertically children of Box layout in Jetpack Compose?

I would like to obtain such a layout, where all the images are centered vertically. For an example:

Box layout centered vertically

Here's how it looks in the code:

    Box(
        modifier = Modifier
            .width(254.dp)
            .height(186.dp)
    ) {
        Image(
            // scaling
        )
        Image(
            // scaling, padding, zIndex
        )
        Image(
            // scaling, padding, zIndex
        )
        Image(
            // scaling, padding, zIndex
        )
        Image(
            // padding, zIndex
        )
    }

Box layout gives possibility to align items inside a bit:

Box(
    modifier = Modifier.align(Alignment.CenterVertically) 
    // But doesn't compile, type mismatch: `Alignment.Horizontal` type is required.
    // Not `Alignment.Vertical`.
)

or

Box(
     contentAlignment = Alignment.CenterVertically,
     // But doesn't compile, type mismatch: `Alignment` type is required.
     // Not `Alignment.Vertical`.
)

But it doesn't compile. If none of the above even compiles, then what should I do? There's no alignment function available for Box, which supports Alignment.CenterVertically...

like image 998
Przemo Avatar asked Dec 06 '25 06:12

Przemo


2 Answers

It turned out, the solution is to not even bother to use Alignment.CenterVertically, but Alignment.CenterStart.

Box(
    contentAlignment = Alignment.CenterStart,
    ...
)

What a surprise. It kinda makes sense, although naming is confusing if you worked with standard non-compose Android Layouts before.

As it turns out, Alignment.CenterVertically is useful for Row layout and its verticalAlignment parameter:

Row(verticalAlignment = Alignment.CenterVertically)
like image 116
Przemo Avatar answered Dec 08 '25 05:12

Przemo


Use

contentAlignment = Alignment.TopCenter // for horizontally center

contentAlignment = Alignment.CenterStart // for vertically center

contentAlignment = Alignment.Center   // for both
like image 39
Aditya Anand Avatar answered Dec 08 '25 07:12

Aditya Anand



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!