我正在尝试实现一个简单的图像网格。
每个图像的大小相同,问题是如果我缩小图像(例如,如果我设置一个 spanCount 以便网格布局必须调整图像大小以适应它们)包含图像的“虚拟单元”不适应图像尺寸。
在这里您可以看到 spanCount=3 和 spanCount=4 之间的差异。
如果我对 imageView 使用 fitXY
这就是结果,因此网格布局管理器会减小单元格宽度,但不适合单元格高度。
我的网格布局 xml:
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/grid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
app:spanCount="4"
tools:itemCount="30"
tools:listitem="@layout/image_item" />
和 image_item.xml
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="fitCenter"
tools:srcCompat="@tools:sample/avatars" />
我的目标:
- 第 1 步:消除列之间的间隙
- 第 2 步:调整图像大小,使其始终适合水平空间(在本例中,spanCount = 3 时,右侧可见一个小空间)
为了更清楚,我需要删除标记为红色的空格。
最佳答案
如果我可以尝试回答这个问题,在您的image_item.xml
中,我建议您将布局宽度更改为match_parent
,如下所示
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="centerCrop"
tools:srcCompat="@tools:sample/avatars" />
这背后的逻辑是因为我们已经使用了 GridLayout 管理器并且我们的 spanCount 是 4,所以 match_parent
宽度将占据所有可用的空间,无论分配的 spanCount 内部如何。
其次,我觉得 centerCrop
会更好。它可以自动调整所有图像,而不会显得它们被拉伸(stretch)。
编辑:
我觉得您可以使用 ConstraintLayout 的魔力来完成此任务,您必须按如下方式更新您的 image_item.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/imageView"
android:layout_width="0dp"
android:layout_height="0dp"
tools:srcCompat="@tools:sample/avatars"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintDimensionRatio="1"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
这里的逻辑是 GridLayout 的 0dp 可以帮助您的图像占据任何可用的宽度,而 dimensionRatio
为 1 可以帮助您的宽度和高度相等。
关于Android,RecyclerView与GridLayoutManager和ImageView作为单元格内容不适合垂直空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67787982/