Skip to content Skip to sidebar Skip to footer

How To Mimick Weighted Linearlayout With A Constraint Layout

How can we spare space equally in a Constraint Layout as in LinearLayout? For instance, how would the below layout become if it was written with constraints?

Solution 1:

FYI -- Constraint Layout alpha 9 added Chains, which allow you to implement this behavior.

enter image description here

Solution 2:

At the moment (constraint layout alpha 6) the only other option to do this is to use vertical guidelines with a percent position, then for each widget constrain them to the guidelines in such a way: Left side <- widget A -> Guideline 1 <- widget B -> Guideline 2 <- widget C -> Right side

With Guideline 1 at 0.33, Guideline 2 at 0.66.

But.

While it works, I doubt it would be faster than using linear layout for this specific task -- if all you want is this exact behaviour, just use linear layout (even inside a constraint layout). The only advantage that it gives you to do it with constraint layout is that you can define this behaviour only for a given axis, the other axis could be constrained completely differently (while for LL it will be aligned -- but that's the common need).

Although we do have plans to make this particular behaviour a lot easier to do in future versions of constraint layout, it doesn't mean that all the existing layouts should never be used anymore.

Solution 3:

For example:

<Button
    android:id="@+id/btn_a"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="ButtonA"
    app:layout_constraintHorizontal_chainStyle="spread"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toLeftOf="@+id/btn_b" />

<Button
    android:id="@+id/btn_b"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="ButtonB"
    app:layout_constraintLeft_toRightOf="@+id/btn_a"
    app:layout_constraintRight_toLeftOf="@+id/btn_c" />

<Button
    android:id="@+id/btn_c"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="ButtonC"
    app:layout_constraintLeft_toRightOf="@+id/btn_b"
    app:layout_constraintRight_toRightOf="parent" />

Post a Comment for "How To Mimick Weighted Linearlayout With A Constraint Layout"