Jetpack Compose 中约束布局的权重

Yan*_*ick 8 android android-jetpack-compose

有没有办法在Jetpack Compose ConstraintLayout 链中使用权重,就像在 XML 中一样:

\n
<android.support.constraint.ConstraintLayout\n    xmlns:android="http://schemas.android.com/apk/res/android"\n    xmlns:app="http://schemas.android.com/apk/res-auto"\n    android:layout_width="match_parent"\n    android:layout_height="match_parent">\n\n    <View\n        android:id="@+id/first"\n        android:layout_width="0dp"\n        android:layout_height="48dp"\n        android:background="#caf"\n        app:layout_constraintLeft_toLeftOf="parent"\n        app:layout_constraintRight_toLeftOf="@+id/start"\n        app:layout_constraintHorizontal_weight="6"/>\n\n    <View\n        android:id="@+id/second"\n        android:layout_width="0dp"\n        android:layout_height="48dp"\n        android:background="#fac"\n        app:layout_constraintLeft_toRightOf="@+id/first"\n        app:layout_constraintRight_toRightOf="parent"\n        app:layout_constraintHorizontal_weight="4"/>\n\n</android.support.constraint.ConstraintLayout>\n\n
Run Code Online (Sandbox Code Playgroud)\n

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

\n

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

\n

注意:据我了解,新的 Jetpack Compose ConstraintLayout 对于复杂的嵌套布局结构(如 Android View ConstraintLayout)没有性能优势。I\xe2\x80\x99m 也知道 Row 和 Column 提供权重功能,但在我的情况下我必须使用 ConstraintLayout (原因

\n

ngl*_*ber 22

你尝试过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)
        )
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 奇迹般有效!多谢。注意:此修饰符将被 `width = Dimension.fillToConstraints` 覆盖,因此请使用其中一个 (3认同)