Search code examples
androidandroid-constraintlayout

How to stick two views together in the center of parent in constraint layout?


I have implemented below layout using linear layout , I want to get same result using constraint layout, how can I do it?


Solution

  • Use chain to configure a group of views that are linked to each other with bi-directional position constraints.

    Official docs: Control linear groups with a chain

    <?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"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        
        
        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button"
            app:layout_constraintBottom_toTopOf="@+id/button3"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_chainStyle="packed" />
        <!-- With packed the views are packed together  -->
        
        <Button
            android:id="@+id/button3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/button2" />
        
    </androidx.constraintlayout.widget.ConstraintLayout>