Search code examples
androidandroid-layoutkotlinandroid-constraintlayout

Android constraint layout include another layout


I am having more of a conceptual question when it comes to ConstraintLayout. I want to re-use a layout inside my ConstraintLayout. But I ask myself a question that the ConstraintLayout aims at avoiding nesting of layouts and including a layout will decrease the ConstraintLayout performance. What is the best/ good practice to avoid nesting of layouts and at the same time re-use a layout so as to avoid code duplication?


Solution

  • You can use <merge/> tag to eliminate redundant view groups in your view hierarchy when including one layout within another.

    Example:

    main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
        
        <include layout="@layout/include_layout"/>
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    

    include_layout.xml

    <?xml version="1.0" encoding="utf-8"?>
    <merge
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto">
    
        <Button
            android:id="@+id/button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="33dp"
            android:text="Button"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="30dp"
            android:text="TextView"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/button" />
    </merge>
    

    Result: enter image description here

    In this case, without the <merge/> tag, you'll have two ConstraintLayout in the layout hierarchy.

    enter image description here

    Reference: https://developer.android.com/training/improving-layouts/reusing-layouts