Android图片以正确的高度填充可用宽度

问题描述

我正在尝试创建一个回收站视图项以并排显示多行图像。

  • [图像1] [图像2] [图像3]
  • [图像4] [图像5] [图像6]
  • [图7] [图8] [图9]

我想避免设置任何宽度或高度,因为我希望图像缩放以填充屏幕的可用宽度。我试图使用纯Android布局XML来做到这一点(即,如果可能的话,不希望通过编程方式做到这一点),并希望避免设置固定的高度。但是,我找不到任何适用的高度设置来实现这一目标。

我总是发现Stack Overflow主题倾向于建议layout_weight,它在图像确实填满可用宽度时“几乎可以工作”,但是包装器的高度太大,仍然是包装器的高度。原始图像。

在下图中看到,蓝线显示了容器的高度,这给了很多意外的边距/填充外观。

是否可以修改以下内容以修剪包装纸的高度以更准确地放置图像?

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/card_1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:src="@drawable/card_ha" />

        <ImageView
            android:id="@+id/card_2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:src="@drawable/card_ha" />

        <ImageView
            android:id="@+id/card_3"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:src="@drawable/card_ha" />
    </LinearLayout>
</layout>

enter image description here

解决方法

您尝试过adjustViewBounds吗?

请参阅,根据official documentation和我的使用经验,adJustViewBounds从xml开始根据图像/可绘制对象的比例调整ImageView's边界/边界如下图所示。

enter image description here

因此,如果您已经将width设置为0dp,将height设置为wrap_content,则ImageView的大小将根据纵横比进行调整。 / p>

要执行此操作:在所有android:adjustViewBounds="true"标签中添加ImageViews。您无需以编程方式或在xml中执行任何其他操作。

此外,如果您想添加更多的图像行,我建议您使用GridView,否则就不需要了。