4

Is there an easy way, without resorting to manual layout or constraint layout, to align children of a Column/Row relative to each other, independently of the Column/Row content alignment?

This what I'm trying to achieve: having a Column that aligns its content to the right. But the children are center-aligned between each other.

Column elements aligned to the right but centered relative to each other

Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841
Mark
  • 81
  • 1
  • 4

2 Answers2

4

You can use something like:

Row(Modifier.fillMaxWidth(),
    horizontalArrangement = Arrangement.End
) {
    Column(horizontalAlignment = Alignment.CenterHorizontally,
    ) {
        Text("Hello")
        Text("H")
        Text("Hello,how are you?")
    }
}

enter image description here

Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841
1

You can wrap the children in a container like the answer above, but I prefer to write custom composables as this is easy to do in Jetpack Compose and you can then reuse them in your app.

You can achieve that with this custom column

@Composable
fun MyColumn(
    modifier: Modifier = Modifier,
    content: @Composable () -> Unit,
) {
    Layout(
        content = content,
        modifier = modifier,
    ) { measurables, constraints ->
        val looseConstraints = constraints.copy(
            minWidth = 0,
            minHeight = 0,
        )
        val placeables = measurables.map { measurable ->
            measurable.measure(looseConstraints)
        }
        val maxChildWidth = placeables.maxByOrNull { it.width }?.width ?: 0
        val height = placeables.sumOf { it.height }
        layout(
            constraints.maxWidth,
            height.coerceAtMost(constraints.maxHeight),
        ) {
            var yPosition = 0
            val maxWidth = constraints.maxWidth
            placeables.forEach { placeable ->
                val deltaX = maxWidth - maxChildWidth + (maxChildWidth - placeable.width) / 2
                placeable.place(deltaX, yPosition)
                yPosition += placeable.height
            }
        }
    }
}

enter image description here

Francesc
  • 25,014
  • 10
  • 66
  • 84