我在 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 的高度,以便我可以计算自定义图像的必要宽度?
谢谢你能读到这里。如果您能指出解决方案的方向,则更加感谢!