Search code examples
androidandroid-viewpagerandroid-constraintlayout

ConstraintLayout inside of ViewPager wrap_content not working


I created a ViewPager and put it inside of ConstraintLayout:

    <androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/green">

    <ViewPager
        android:id="@+id/teaser_view_pager"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:clipToPadding="false"
        android:background="@color/blue"
        android:currentPage="@={viewModel.currentItem}"
        bind:adapter="@{viewModel.adapter}"
        bind:withAnimation="@{viewModel.changeWithAnimation}"
        bind:layout_constraintStart_toStartOf="parent"
        bind:layout_constraintTop_toTopOf="parent"
        bind:layout_constraintEnd_toEndOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

and the layout of item inside of ViewPager is:

    <androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/red">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:scaleType="fitCenter"
        android:background="@color/black"
        bind:imageUrl="@{viewModel.imagePath}"
        bind:layout_constraintDimensionRatio="3:1"
        android:adjustViewBounds="true" />

</androidx.constraintlayout.widget.ConstraintLayout>

as you see, every view or it's parent has different background. And if I run the app, I see:

red background

the background is red, it means, the ConstraintLayout in ViewPager item is stretched to the whole height of screen despite wrap_content. Anybody knows, how to shrink the item to the size of the image inside?

P.S.: I use ConstraintLayout here, because I need to keep the image size in aspect ratio "3:1"


Solution

  • Set all constraints to parent then use 0dp in height or width instead of `wrap_content'