1

I have a GridView that I am using to display a row of 4 images, each image is 200 x 200 pixels. Here is the layout xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <GridView
        android:id="@+id/myGridView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:numColumns="4" >
    </GridView>

</RelativeLayout>

When I run my app here is what the images look like:

grid view with 4 images

As you can see the images are getting scaled (narrowed) to fit the screen.

How do I make it so the images are stretched both vertically and horizontally to maintain the correct aspect ratio?

Note that I am using an adapter to draw the images:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ImageView imageView;
    if (convertView == null) {
        imageView = new ImageView(context);
    } else {
        imageView = (ImageView) convertView;
    }
    imageView.setBackgroundResource(imageIds[position]);
    return imageView;
}
1
  • 1
    Have You tried to sue imageView.setImageResource instead of setBackgroundResource ?
    – sandrstar
    Mar 16, 2013 at 3:52

1 Answer 1

3

I got the same issue in last weak.Use my image view class and solve this issue.

public class iv_autoSizedImageView extends ImageView {

    public iv_autoSizedImageView(Context context, AttributeSet attrs) {
        super(context, attrs);

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        // TODO Auto-generated method stub
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        try {

            getLayoutParams().height = getMeasuredWidth();

        } catch (Exception e) {
            // TODO: handle exception

        }

    }

}

layout.xml

 <com.sample.test.iv_autoSizedImageView
            android:id="@+id/IV_NEWS_IMAGE"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"/>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.