Jetpack Compose中约束布局的权重



是否有任何方法可以在Jetpack ComposeConstraintLayout链中使用权重,如XML:

<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(原因(

你试过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)
)
}
}

您可能需要使用Modifier.horizontalChainWeight = 1f

最新更新