【发布时间】:2011-07-18 07:52:51
【问题描述】:
我在 LinearLayout 中有几个 ImageView。我需要按比例缩小 ImageView,以便它们保持纵横比,同时垂直适合 LinearLayout。在水平方向上,我只需要它们彼此相邻。
我为此制作了一个简化的测试台,它嵌套了加权布局,因此我有一个宽但不是很高的 ImageView 线性布局 -
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent">
<LinearLayout android:id="@+id/linearLayout1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="5">
<LinearLayout android:id="@+id/linearLayout3" android:layout_height="fill_parent" android:layout_width="fill_parent" android:layout_weight="1">
<ImageView android:id="@+id/imageView1" android:layout_height="wrap_content" android:layout_width="wrap_content" android:src="@drawable/test_image" android:scaleType="fitStart"></ImageView>
<ImageView android:id="@+id/imageView2" android:layout_height="wrap_content" android:layout_width="wrap_content" android:src="@drawable/test_image" android:scaleType="fitStart"></ImageView>
</LinearLayout>
<LinearLayout android:id="@+id/linearLayout4" android:layout_height="fill_parent" android:layout_width="fill_parent" android:layout_weight="1"></LinearLayout>
</LinearLayout>
<LinearLayout android:id="@+id/linearLayout2" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1"></LinearLayout>
</LinearLayout>
(在 Eclipse 布局编辑器中,图像被垂直剪切,根本没有缩放 - 但这只是我们学会喜欢的那些特质之一)
在硬件上运行时,图像会缩放到正确的高度,同时保持它们的纵横比。我的问题是它们不是相邻的。每个 ImageView 的高度与 LinearLayout 的高度正确匹配。每个 ImageView 的宽度是未缩放图像的宽度 - 实际缩小的图像出现在其 ImageView 的左侧。因此,图像之间的差距很大。
理想情况下,我希望通过 XML 进行管理,但如果无法做到这一点,我知道使用自定义视图可能是最好的解决方案。
我尝试创建一个覆盖 onMeasure 的 IconView(扩展 ImageView)类,以便我可以通过根据高度缩放宽度来创建必要大小的图像视图。但是传入函数的 parentWidth 和 parentHeight 是屏幕的尺寸,而不是 LinearLayout 容器的尺寸。
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
// Calculations followed by calls to setMeasuredDimension, setLayoutParams
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
所以我的问题是 -
1) 我可以通过某种方式修改 XML 以使其满足我的需要吗?
2) 如何让我的自定义类获得 LinearLayout 的高度,以便计算自定义图像所需的宽度?
感谢您能读到这里。如果您能指出解决方案的方向,将更加感谢!
【问题讨论】:
-
非常感谢,我遇到了类似的问题:我想要的只是应用顶部的一张图片,使用全宽。由于一些未知的原因,imageView 几乎是图像本身的两倍,挡住了宝贵的屏幕空间。感谢添加
android:adjustViewBounds="true"图片高度调整 -
@dave
android::adjustViewBounds默认没有设置为 true 很奇怪。很高兴您的问题现在得到了解决。
标签: android layout formatting imageview custom-view