Jetpack Compose如何使Row/Column中的子元素相对于彼此对齐

4
有没有一种简单的方法,不用手动布局或约束布局,可以使 Column/Row 的子元素相对于彼此对齐,而与 Column/Row 内容的对齐方式无关?
这就是我想要实现的:有一个将其内容右对齐的 Column。但是子元素在彼此之间居中对齐。

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

2个回答

4
您可以使用类似以下的方法:
Row(Modifier.fillMaxWidth(),
    horizontalArrangement = Arrangement.End
) {
    Column(horizontalAlignment = Alignment.CenterHorizontally,
    ) {
        Text("Hello")
        Text("H")
        Text("Hello,how are you?")
    }
}

enter image description here


1
你可以像上面的答案一样将子组件包装在一个容器中,但我更喜欢编写自定义组合函数,因为在Jetpack Compose中很容易实现,并且可以在应用程序中重复使用它们。
你可以通过这个自定义列来实现。
@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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接