How to have a view in ConstraintLayout behave as both wrap_content and match_parent depending on visibility of another view

As you can see in the image below, I'm looking for a way to have 2 views, and I need that when both are visible, view 2 behave as a wrap_parent, but when view 1 is gone, I will like to view 2 to take the remaining of the space.

I know constraint layout can accomplish this; I haven't found a way to do it.

Here is an example of what I'm looking forenter image description here

Edit 1

Neither of these views is view groups.

Answers 1

  • Place both views into a horizontal chain that is spread_inside. Set the width of both views to 0dp. For View 2, specify app:layout_constraintWidth_min="wrap". For View 1 set the layout weight (app:layout_constraintHorizontal_weight) to 1.

    The following XML is an example:

    <androidx.constraintlayout.widget.ConstraintLayout 
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <TextView
            android:id="@+id/textView1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:background="@android:color/holo_green_light"
            android:text="View 1"
            android:textSize="24sp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toStartOf="@+id/textView2"
            app:layout_constraintHorizontal_chainStyle="spread_inside"
            app:layout_constraintHorizontal_weight="1"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            tools:visibility="visible" />
    
        <TextView
            android:id="@+id/textView2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginEnd="16dp"
            android:background="@android:color/holo_blue_light"
            android:text="View 2"
            android:textSize="24sp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toEndOf="@+id/textView1"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintWidth_min="wrap" />
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    

    When both views are visible, we see this:

    enter image description here

    With View 1 gone, we see this:

    enter image description here


Related Articles