我想知道您使用什么容器小部件来保存 ImageView。
例如... GridView、ListView 等...
如果您使用 GridView,您尝试通过 GridView.setNumColumns() 设置列数。
如果仍然不起作用,您尝试通过多种方式之一使用 AspectRatioFrameLayout 类。
这个类很简单。请按照以下步骤操作!
1.在res/attrs.xml中添加属性
<declare-styleable name="AspectRatioFrameLayout">
<attr name="aspectRatio" format="float" />
</declare-styleable>
2.创建AspectRatioFrameLayout类
public class AspectRatioFrameLayout extends FrameLayout {
private static final String TAG = "AspectRatioFrameLayout";
private static final boolean DEBUG = false;
private float mAspectRatio; // width/height ratio
public AspectRatioFrameLayout(Context context) {
super(context);
}
public AspectRatioFrameLayout(Context context, AttributeSet attrs) {
super(context, attrs);
initAttributes(context, attrs);
}
public AspectRatioFrameLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initAttributes(context, attrs);
}
private void initAttributes(Context context, AttributeSet attrs) {
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.AspectRatioFrameLayout);
mAspectRatio = typedArray.getFloat(R.styleable.AspectRatioFrameLayout_aspectRatio, 1.0f);
typedArray.recycle();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
if (DEBUG) Log.d(TAG, "widthMode:"+widthMode+", heightMode:"+heightMode);
if (DEBUG) Log.d(TAG, "widthSize:"+widthSize+", heightSize:"+heightSize);
if ( widthMode == MeasureSpec.EXACTLY && heightMode == MeasureSpec.EXACTLY ) {
// do nothing
} else if ( widthMode == MeasureSpec.EXACTLY ) {
heightMeasureSpec = MeasureSpec.makeMeasureSpec((int)(widthSize / mAspectRatio), MeasureSpec.EXACTLY);
} else if ( heightMode == MeasureSpec.EXACTLY ) {
widthMeasureSpec = MeasureSpec.makeMeasureSpec((int)(heightSize * mAspectRatio), MeasureSpec.EXACTLY);
} else {
// do nothing
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
3.修改list_item_image.xml
<your.package.AspectRatioFrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_height="match_parent"
android:layout_width="match_parent"
app:aspectRatio="1">
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/imageView"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:src="@drawable/locked_image"
android:scaleType="fitXY"
/>
</your.package.AspectRatioFrameLayout>