这是一个简单的布局:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/companyIcon"
android:layout_width="wrap_content"
android:layout_height="40dp" <!-- notice I've limited a height -->
android:scaleType="fitStart"
android:adjustViewBounds="true"
android:layout_alignParentLeft="true" />
<TextView
android:id="@+id/companyName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/companyIcon"
android:layout_marginLeft="3dp"
android:layout_centerVertical="true"
android:textStyle="bold"
android:textColor="#20526d" />
</RelativeLayout>
我将通过 setImageBitmap()
设置的图像高度超过 40dp。
使用这种布局,我在 ImageView
和 TextView
之间有一个额外的空间,它是从哪里来的?
但是在我用 FrameLayout
包装 ImageView
之后,我没有这个不必要的额外空间:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<FrameLayout
android:id="@+id/image_container"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/companyIcon"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:scaleType="fitStart"
android:adjustViewBounds="true"
android:layout_alignParentLeft="true" />
</FrameLayout>
<TextView
android:id="@+id/companyName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/image_container"
android:layout_marginLeft="3dp"
android:layout_centerVertical="true"
android:textStyle="bold"
android:textColor="#20526d" />
</RelativeLayout>
结果:
你们能解释一下为什么我要将 ImageView
放入 FrameLayout
以达到预期效果吗?非常感谢。
最佳答案
The height of an image I will set by setImageBitmap() is more that 40dp. Using this layout I have an extra space between ImageView and TextView, where did it come from?
由于带有 android:scaleType="fitStart"
的 android:layout_height="40dp"
,图像被缩小(并且向左/开始)为了适应高度,所以这个“额外空间”实际上是图像的原始宽度,因为你的 android:layout_width="wrap_content"
。我用我自己的大于 40dp
的图像重新创建了您的布局。当您选择 ImageView
时,您可以看到它的边界拉伸(stretch)到图像的原始宽度。
为了进一步证明这一点,如果我设置 android:scaleType="center"
,则不应用任何拟合,您可以看到 ImageView
的原始宽度。
Can you guys explain why shall I put ImageView into FrameLayout to have things as intended?
看来,由于您的 FrameLayout
使用 android:layout_width="wrap_content"
,它会在之后从您的 ImageView
获得正确的缩小宽度它由于 android:adjustViewBounds="true"
而被缩放。奇怪的是 ImageView
本身使用 android:layout_width="wrap_content"
,但显示的是原始图像的宽度,而不是缩放后的宽度。我的预感是 ImageView
的高度和宽度在 应用缩放之前设置,所以 ImageView
获取原始图像的宽度,但父 FrameLayout
获取其 ImageView
子 在应用缩放之后 的缩放宽度。这可能不是真的,但在我看来是这样的。
但是,您可以通过在 ImageView
上使用 android:maxHeight="40dp"
来解决未缩放的宽度问题(不使用 FrameLayout
) >。然后您可以设置 android:layout_height="wrap_content"
如果图像较小,您的图像可以小于 40dp
。
<ImageView
android:id="@+id/companyIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:adjustViewBounds="true"
android:maxHeight="40dp"
android:scaleType="fitStart" />
关于android - 为什么我需要将 ImageView 包装到 FrameLayout 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14609106/