首页 > 解决方案 > 行内的 fillMaxHeight()

问题描述

我的问题与这个有关:如何在 Jetpack Compose 中实现这种布局

我有这个代码:

@Composable
fun TestUi() {
    Row {
        Box(
            contentAlignment = Alignment.Center,
            modifier = Modifier
                .background(color = Color.Yellow)
                .fillMaxHeight()
        ) {
            CircularProgressIndicator()
        }
    
        Image(imageVector = vectorResource(id = R.drawable.ic_launcher_background))
    }
}

我希望得到这个:

预期结果

但我得到了这个:

实际结果

如何让 Box 填充所有可用高度而不影响 Row 的高度?

我知道我可以使用 ConstraintLayout 来解决这个问题,但是对于这样一个简单的用例来说似乎太多了。

标签: android-jetpack-compose

解决方案


看看 Layout Composable 或 Modifier。您可以先测量定义元素,然后为从属元素提供修改后的约束。如果您想将其用作修饰符,则应为列表添加大小检查。

Layout(content = {
    Box(modifier = Modifier
        .size(width = 30.dp, height = 50.dp)
        .background(Color.Green))
    Box(
        contentAlignment = Alignment.Center,
        modifier = Modifier
            .background(color = Color.Yellow)
            .fillMaxHeight()
    ) {
        CircularProgressIndicator()
    }
}) { measurables: List<Measurable>, constraints: Constraints ->
    val heightDef = measurables[0].measure(constraints)
    val other = measurables[1].measure(
        constraints.copy(
            maxHeight = heightDef.height,
            maxWidth = constraints.maxWidth - heightDef.width)
    )
    layout(
        width = heightDef.width + other.width,
        height = heightDef.height
    ) {
        other.placeRelative(0,0)
        heightDef.placeRelative(other.width,0)
    }
}

推荐阅读