我需要在屏幕顶部并排(无间隙)显示三个相同尺寸的图像 (200 X 100)。它们应该占据屏幕的整个宽度并保持宽高比。 是否可以仅使用布局 xml 文件来实现这一点,或者我需要使用 java 代码?
解决方案应该与分辨率无关...任何人都可以发布此(或类似)问题的解决方案或链接吗?谢谢!
请您参考如下方法:
成功了!但正如我上面所说,您需要创建自己的类。但它很小。我在 Bob Lee 在这篇文章中的回答的帮助下创建了它:Android: How to stretch an image to the screen width while maintaining aspect ratio?
package com.yourpackage.widgets;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageView;
public class AspectRatioImageView extends ImageView {
public AspectRatioImageView(Context context) {
super(context);
}
public AspectRatioImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public AspectRatioImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = width * getDrawable().getIntrinsicHeight() / getDrawable().getIntrinsicWidth();
setMeasuredDimension(width, height);
}
}
现在在 XML 中使用它:
<com.yourpackage.widgets.AspectRatioImageView
android:id="@+id/image"
android:src="@drawable/yourdrawable"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:adjustViewBounds="true" />
玩得开心!
========================================
找到了另一种仅在 XML 中使用 android:adjustViewBounds="true"执行相同操作的方法。这是一个例子:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:adjustViewBounds="true"
android:src="@drawable/image1" />
<ImageView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:adjustViewBounds="true"
android:src="@drawable/image2" />
<ImageView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:adjustViewBounds="true"
android:src="@drawable/image2" />
</LinearLayout>