I wonder which container widget you use to store ImageView.
e.g. ... GridView, ListView, etc.
If you are using a GridView, you are trying to set the number of columns using GridView.setNumColumns ().
If still not working, you are trying to use the AspectRatioFrameLayout class in one of many ways.
this class is simple. follow these steps!
1. Add attributes to res / attrs.xml
<declare-styleable name="AspectRatioFrameLayout"> <attr name="aspectRatio" format="float" /> </declare-styleable>
2. create an AspectRatioFrameLayout class
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. Modify 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>
Hogun source share