me.at.coding
me.at.coding

Reputation: 17744

How to constrain a View below two Views whose visibility can be switched?

Image a ConstraintLayout which includes three vertically stacked items:

@+id/top
@+id/middle1 or @+id/middle2 (one gets View.VISIBLE, one gets View.GONE)
@+id/bottom

The top of @+id/middle1 and @+id/middle2 is constrained to the bottom of @+id/top, no issue here.

The interesting case is @+id/bottom. That shall always be placed below @+id/middle1 or @+id/middle2, depending on which one is visible (the other will get View.GONE). Is there any way to model this in the layout file or do I have to change the top constraint for @+id/bottom while switching between showing @+id/middle1 and @+id/middle2?

Upvotes: 9

Views: 2010

Answers (1)

me.at.coding
me.at.coding

Reputation: 17744

As proposed by CommonsWare, it can be done with a Barrier as follows:

 <androidx.constraintlayout.widget.Barrier
          android:id="@+id/barrier"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          app:barrierDirection="bottom"
          app:barrierAllowsGoneWidgets="false"
          app:constraint_referenced_ids="middle1,middle2" />

Note that the IDs in app:constraint_referenced_ids are written without the @id/ prefix.

As my middle1 and middle2 have different heights and I set one of them to View.GONEI went with app:barrierAllowsGoneWidgets="false" to make sure that the Barrier position gets updated and no blank space is left over.

For more details see the official documentation or e.g. on Youtube the video ConstraintLayout Tutorial Part 4 - BARRIERS AND GROUPS - Android Studio Tutorial

Upvotes: 10

Related Questions