Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android constraint layout not working as intended

I have an activity with a root tag of

androidx.constraintlayout.widget.ConstraintLayout

I include 3 layout files in this activity and list them vertically. The following constraints on the middle one does not work

    app:layout_constraintTop_toBottomOf="@+id/lay1"
    app:layout_constraintBottom_toTopOf="@+id/lay3"

I don't understand why the middle one takes the entire screen instead of starting from the bottom of the top one and ending at top of the bottom one. Can you please help me?

The activity:

<androidx.constraintlayout.widget.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">

    <include
        android:id="@+id/lay1"
        layout="@layout/empty_linear_layout"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <include
        android:id="@+id/lay2"
        layout="@layout/empty_linear_layout"
        app:layout_constraintBottom_toTopOf="@+id/lay3"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/lay1" />

    <include
        android:id="@+id/lay3"
        layout="@layout/empty_linear_layout"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

empty_linear_layout.xml :

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:text="button" />

</LinearLayout>
like image 939
M. Azyoksul Avatar asked Aug 03 '19 14:08

M. Azyoksul


Video Answer


1 Answers

If you want to override layout_ parameters on an <include> layout, you have to specify both layout_width and layout_height. From the developer docs:

However, if you want to override layout attributes using the <include> tag, you must override both android:layout_height and android:layout_width in order for other layout attributes to take effect.

So add these two lines to your second view:

android:layout_width="0dp"
android:layout_height="0dp"

(Note that for ConstraintLayout, 0dp means to match the constraints)

like image 169
Ben P. Avatar answered Sep 23 '22 12:09

Ben P.