androidandroid-constraintlayoutviewstub

How to use ViewStub in ConstraintLayout?


It seems that when inflating a ViewStub in a ConstraintLayout, the resulting view has lost all its constraints. I guess we can define the constraints for the inflated view using ConstraintSet, but that kind of defeats the purpose of ViewStub.

Is there a good way to do this?


Solution

  • There's a simple solution:

    in your ViewStub let the inflatedId attribute as the same as id

    like this:

    <ViewStub
        android:id="@+id/pocket_view"
        android:inflatedId="@+id/pocket_view"
        android:layout="@layout/game_pocket_view"
        android:layout_width="@dimen/game_pocket_max_width"
        android:layout_height="@dimen/game_pocket_max_height"
        app:layout_constraintLeft_toLeftOf="@id/avatar_view"
        app:layout_constraintRight_toRightOf="@id/avatar_view"
        app:layout_constraintTop_toTopOf="@id/avatar_view"
        app:layout_constraintBottom_toBottomOf="@id/avatar_view"
        />