Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GridView with square items in android with adaptive width/height

I have a custom gridview with items like that

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="false"
android:focusable="false"
android:focusableInTouchMode="false"
android:gravity="center"
android:longClickable="false"
android:orientation="vertical" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:clickable="false"
    android:focusable="false"
    android:focusableInTouchMode="false"
    android:longClickable="false"
    android:text="0"
    android:textSize="60sp" />

 </LinearLayout>

I want my items to be squares and I want gridview to stretch width to fill all all width of screen in portrait orientation and all height in landscape orientation. It should look like this layout

Where A - is the side of a square and B is the margin width (it could be zero). I think that I should probably override onMeasure method, but what exactly should I do? Maybe anyone can help?

EDIT OK, I tried to set width and height of items manually in getView method of adapter, it's better, but still it's not what I wanted. How can I get rid of that spacing between columns?

enter image description here

like image 385
user1685095 Avatar asked Oct 31 '13 16:10

user1685095


1 Answers

First, you're want to create a custom View class that you can use instead of the default LinearLayout you're using. Then you want to override the View's onMeasure call, and force it to be square:

public class GridViewItem extends ImageView {

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

  public GridViewItem(Context context, AttributeSet attrs) {
      super(context, attrs);
  }

  public GridViewItem(Context context, AttributeSet attrs, int defStyle) {
      super(context, attrs, defStyle);
  }

  @Override
  public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
      super.onMeasure(widthMeasureSpec, widthMeasureSpec); // This is the   key that will make the height equivalent to its width
  }
}

Then you can change your row_grid.xml file to:

<path.to.item.GridViewItem xmlns:android="http://schemas.android.com/apk/res/android"
   android:id="@+id/item_image"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:scaleType="centerCrop"
   android:src="@drawable/ic_launcher" >
</path.to.item.GridViewItem>

Just be sure to change "path.to.item" to the package where your GridViewItem.java class resides.

Edit:

Also changed scaleType from fitXY to centerCrop so that your image doesn't stretch itself and maintains its aspect ratio. And, as long as it's a square image, nothing should be cropped, regardless.

like image 170
Shirish Herwade Avatar answered Sep 28 '22 05:09

Shirish Herwade