0

I'm using GridView in my app:

<GridView
    android:id="@+id/main_grid_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:numColumns="4" >
</GridView>

Every cell in this GridView is ImageView:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ImageView
        android:id="@+id/img"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:contentDescription="@string/img"
        android:scaleType="centerCrop" />

</RelativeLayout>

All cells in my GridView must be square (height must equals width) and image must fit cell. But it always looks like rectangle... How I can to implements square cells in GridView?

BArtWell
  • 4,176
  • 10
  • 63
  • 106

3 Answers3

1

Make sure your cell is square.

For this, you can set the width and height of the RelativeLayout programmatically with the value screen_width/4.

lpmfilho
  • 178
  • 6
0

This can do the trick

@Override public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int width = MeasureSpec.getSize(widthMeasureSpec);
    int height = MeasureSpec.getSize(heightMeasureSpec);
    int size = width > height ? height : width;
    setMeasuredDimension(size, size);
}
An-droid
  • 6,433
  • 9
  • 48
  • 93
0

As mentioned in the answer here - Gridview with two columns and auto resized images

You can make a custom ImageView for this

public class SquareImageView extends ImageView {

public SquareImageView(Context context) {
    super(context);
}

public SquareImageView(Context context, AttributeSet attributeSet) {
    super(context, attributeSet);
}

public SquareImageView(Context context, AttributeSet attributeSet, int defStyle) {
    super(context, attributeSet, defStyle);
}

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

    if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
        setMeasuredDimension(getMeasuredWidth(), getMeasuredWidth());
    } else {
        setMeasuredDimension(getMeasuredHeight(), getMeasuredHeight());
    }
}
}

and then use this in your grid view cell layout as

<package_containing_SquareImageView.SquareImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
Community
  • 1
  • 1
Darshan Dorai
  • 659
  • 8
  • 10