Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Square layout on GridLayoutManager for RecyclerView

I try to make a grid-layout with square images. I thought that it must be possible to manipulate the GridLayoutManager by manipulating onMeasure to do a

super.onMeasure(recycler, state, widthSpec, widthSpec);  

instead of

super.onMeasure(recycler, state, widthSpec, heightSpec); 

but unfortunately, that didn't work.

Any ideas?

like image 830
Paul Woitaschek Avatar asked Oct 25 '14 20:10

Paul Woitaschek


People also ask

How do you make the first item of RecyclerView of full width with a GridLayoutManager?

You just have to add spanSizeLookup command which will look at the desired position (in our case, it's 0, first pos) and set the span size of layout manager items in RecyclerView. All you need to take care is that the layout manager for your recyclerView should be GridLayoutManager. The rest of your code remains same.


1 Answers

To have the square elements in my RecyclerView, I provide a simple wrapper for my root View element; I use the following SquareRelativeLayout in place of RelativeLayout.

package net.simplyadvanced.widget;  import android.content.Context; import android.util.AttributeSet; import android.widget.RelativeLayout;  /** A RelativeLayout that will always be square -- same width and height,  * where the height is based off the width. */ public class SquareRelativeLayout extends RelativeLayout {      public SquareRelativeLayout(Context context) {         super(context);     }      public SquareRelativeLayout(Context context, AttributeSet attrs) {         super(context, attrs);     }      public SquareRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) {         super(context, attrs, defStyleAttr);     }      @TargetApi(VERSION_CODES.LOLLIPOP)     public SquareRelativeLayout(Context context, AttributeSet attrs,         int defStyleAttr, int defStyleRes) {         super(context, attrs, defStyleAttr, defStyleRes);     }      @Override     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {         // Set a square layout.         super.onMeasure(widthMeasureSpec, widthMeasureSpec);     }  } 

Then, in my XML layout for the adapter, I've just referenced the custom view as shown in the following. Though, you can do this programmatically also.

<?xml version="1.0" encoding="utf-8"?> <net.simplyadvanced.widget.SquareRelativeLayout     xmlns:android="http://schemas.android.com/apk/res/android"     android:id="@+id/elementRootView"     android:layout_width="wrap_content"     android:layout_height="wrap_content">      <!-- More widgets here. -->  </net.simplyadvanced.widget.SquareRelativeLayout> 

Note: Depending on which orientation your grid is, then you may want to have the width based off of height (GridLayoutManager.HORIZONTAL) instead of the height being based off the width (GridLayoutManager.VERTICAL).

like image 127
Anonsage Avatar answered Sep 21 '22 01:09

Anonsage