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

Viewed 1885

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

Box layout centered vertically

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`.
)

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

1 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)
Related