Search code examples
androidandroid-constraintlayout

Setting max height for only one ConstraintLayout chain view


I have two views in a vertical chain in ConstraintLayout with spread_inside chain style. I want to set a max height using layout_constraintHeight_max for the first view only, but since it's the head of the chain it applies to all chained views.

How do I only apply a max height constraint to the first view of the chain?


Solution

  • That behavior of layout_constraintHeight_max is counter-intuitive. Try the following layout that should simulate a chain without the annoying layout_constraintHeight_max behavior. It uses a barrier to mark the top of the bottom view.

    <androidx.constraintlayout.widget.ConstraintLayout 
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <TextView
            android:id="@+id/topView"
            android:layout_width="200dp"
            android:layout_height="0dp"
            android:background="@android:color/holo_blue_light"
            app:layout_constraintBottom_toTopOf="@id/barrier"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHeight_max="200dp"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            tools:text="This is the top view." />
    
        <TextView
            android:id="@+id/bottomView"
            android:layout_width="200dp"
            android:layout_height="0dp"
            android:background="@android:color/holo_red_light"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHeight_min="100dp"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@id/topView"
            tools:text="This is the bottom view." />
    
        <androidx.constraintlayout.widget.Barrier
            android:id="@+id/barrier"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:barrierDirection="top"
            app:constraint_referenced_ids="bottomView" />
    </androidx.constraintlayout.widget.ConstraintLayout>
    

    You say that the top view can shrink down to 0dp. If you mean zero height, then the foregoing may not go that far by itself.