Issue
Is there any way to use weights in Jetpack Compose ConstraintLayout chains like in 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>
Currently, neither ConstraintLayoutScope
or ConstraintScope
provide weight functionality. ConstraintLayoutScope
provides createHorizontalChain(vararg elements: ConstraintLayoutReference, chainStyle: ChainStyle)
(or createVerticalChain
respectively) but without the option to set weights to individual elements.
With guidelines, barriers and everything else integrated I feel like there's something important missing here. Is there a way to use weights in chains or emulate their behaviour? I cannot just specify a fixed width for a element since the width of the ConstraintLayout has to match the whole screen.
Note: I understand that the new Jetpack Compose ConstraintLayout does not have a performance advantage for complex, otherwise nested, layout structures like the Android View ConstraintLayout had. I’m also aware that Row and Column provide weight functionality but I have to use ConstraintLayout in my case (reason)
Solution
Have you tried fillMaxWidth(faction)
modifier?
I did this and worked for me...
@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)
)
}
}
Answered By - nglauber
Answer Checked By - Pedro (JavaFixing Volunteer)