Paul Woitaschek Paul Woitaschek - 1 year ago 708
Android Question

Recyclerview - GridLayoutManager: Set square dimensions

I try to make a grid-layout with square images. I thought that it must be possible to maniuplate 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 didnt work. Any ideas?

Answer Source

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) {

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

    public SquareRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

    public SquareRelativeLayout(Context context, AttributeSet attrs,         int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);

    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"?>

    <!-- More widgets here. -->


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).