首页 > 解决方案 > ViewPager wrap_content 内的 ConstraintLayout 不起作用

问题描述

我创建了一个 ViewPager 并将其放在 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>

ViewPager 内部项目的布局是:

    <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>

如您所见,每个视图或其父视图都有不同的背景。如果我运行该应用程序,我会看到:

红色背景

背景是红色的,这意味着 ViewPager 项目中的 ConstraintLayout 被拉伸到屏幕的整个高度,尽管wrap_content. 任何人都知道,如何将项目缩小到内部图像的大小?

PS:我在这里使用ConstraintLayout,因为我需要将图像尺寸保持在纵横比“3:1”

标签: androidandroid-viewpagerandroid-constraintlayout

解决方案


设置所有约束,parent 然后0dp在高度或宽度中使用,而不是 `wrap_content'


推荐阅读