androidandroid-jetpack-composeandroid-jetpack

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


Solution

  • 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)