Jetpack Compose 中约束布局的权重

时间:2021-01-10 20:23:18

标签: android android-jetpack-compose

有什么方法可以像在 XML 中一样在 Jetpack Compose ConstraintLayout 链中使用权重:

<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <View
        android:id="@+id/first"
        android:layout_width="0dp"
        android:layout_height="48dp"
        android:background="#caf"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toLeftOf="@+id/start"
        app:layout_constraintHorizontal_weight="6"/>

    <View
        android:id="@+id/second"
        android:layout_width="0dp"
        android:layout_height="48dp"
        android:background="#fac"
        app:layout_constraintLeft_toRightOf="@+id/first"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintHorizontal_weight="4"/>

</android.support.constraint.ConstraintLayout>

目前,ConstraintLayoutScopeConstraintScope 均不提供权重功能。 ConstraintLayoutScope 提供 createHorizontalChain(vararg elements: ConstraintLayoutReference, chainStyle: ChainStyle)(或分别为 createVerticalChain),但没有为单个元素设置权重的选项。

通过整合指南、障碍和其他所有内容,我觉得这里缺少一些重要的东西。有没有办法在链中使用权重或模拟它们的行为?我不能只为一个元素指定一个固定的宽度,因为 ConstraintLayout 的宽度必须匹配整个屏幕。

注意:我知道新的 Jetpack Compose ConstraintLayout 对于像 Android View ConstraintLayout 这样的复杂的嵌套布局结构没有性能优势。我也知道 Row 和 Column 提供权重功能,但在我的情况下我必须使用 ConstraintLayout (reason)

1 个答案:

答案 0 :(得分:2)

您是否尝试过 fillMaxWidth(faction) 修饰符? 我这样做并为我工作...

@Composable
fun ConstraintLayoutWeightDemo() {
    ConstraintLayout(modifier = Modifier.fillMaxWidth()) {
        val (refB1, refB2, refB3) = createRefs()
        Text(
            "Text 1",
            modifier = Modifier
                .constrainAs(refB1) {
                    start.linkTo(parent.start)
                    end.linkTo(refB2.start)
                }
                .fillMaxWidth(.3f) // <<<---- 30%
                .background(Color.Red)
        )
        Text(
            "Text 2",
            modifier = Modifier
                .constrainAs(refB2) {
                    start.linkTo(refB1.end)
                    end.linkTo(refB3.start)
                }
                .fillMaxWidth(.5f) // <<<---- 50%
                .background(Color.Green)
        )
        Text(
            "Text 3",
            modifier = Modifier
                .constrainAs(refB3) {
                    start.linkTo(refB2.end)
                    end.linkTo(parent.end)
                }
                .fillMaxWidth(.2f) // <<<---- 20%
                .background(Color.Blue)
        )
    }
}