Consider following xml layout:
<?xml version="1.0" encoding="utf-8"?>
<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">
<Button
android:id="@+id/b1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="B1"
app:layout_constraintHorizontal_weight="1"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toLeftOf="@+id/b2"/>
<Button
android:id="@+id/b2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="B2"
app:layout_constraintLeft_toRightOf="@+id/b1"
app:layout_constraintRight_toLeftOf="@id/b3"/>
<Button
android:id="@+id/b3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="B3"
app:layout_constraintLeft_toRightOf="@+id/b2"
app:layout_constraintRight_toRightOf="parent"/>
</android.support.constraint.ConstraintLayout>
which produces this layout which is what I want:
But if I mark B3 as gone then B1's width is set to 0 and B2 move to left. Whereas I want B2 to take B3's place and B1 to expand:
Any idea what I might be doing wrong?
If you have the choice start with ConstraintLayout, but if you already have your app in RelativeLayout, stay with it. That's all I have been following. RelativeLayout is very limited in functionality and many complex layouts can't be made using it, especially when ratios are involved.
To set the Weight in the Constraint Layout, the child View (and not the parent View) must be selected. And instead of selecting all child Views, you can set Weight to a subset which are variable. You can select multiple child Views by holding down the Ctrl key while selecting the Views.
You can create linear layouts now with ConstraintLayout by constraining the sides of each element with each other. The quick way of creating these layouts is to select all the views together and right click to center horizontally or vertically.
Chains are a specific kind of constraint which allow us to share space between the views within the chain and control how the available space is divided between them. The closest analogue with traditional Android layouts is weights in LinearLayout , but chains do far more than that, as we shall see.
set android:layout_width = "0dp"
and app:layout_constraintHorizontal_weight="1"
for B2 and you are set to go.
EDIT: Just remove app:layout_constraintRight_toLeftOf="@id/b3"
from B2.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With