我在LinearLayout中有一些ImageView.我需要缩小ImageViews,以便它们保持纵横比,同时垂直安装在LinearLayout内部.水平地,我只需要它们彼此相邻.
我为此制作了一个简化的测试床,它嵌套了加权的布局,这样我就可以为ImageViews提供一个宽但不高的LinearLayout -
<?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>
Run Code Online (Sandbox Code Playgroud)
(在Eclipse布局编辑器中,图像被垂直剪切而根本没有缩放 - 但这只是我们学会爱的那些特性之一)
在硬件上运行时,图像会缩放到正确的高度,同时保留其纵横比.我的问题是他们不是彼此相邻的.每个ImageView的高度正确匹配LinearLayout的高度.每个ImageView的宽度是未缩放图像的宽度 - 实际按比例缩小的图像出现在其ImageView的左侧.因此,我在图像之间会有很大的差距.
理想情况下,我想通过XML来管理这个,如果这是不可能的,我理解使用自定义视图可能是最好的解决方案.
我尝试创建一个IconView(扩展ImageView)类来覆盖onMeasure,这样我就可以通过根据高度缩放宽度来创建所需大小的图像视图.但是传递给函数的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); …Run Code Online (Sandbox Code Playgroud)