Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Equal column spacing in a RecyclerView with GridLayoutManager
package com.example.columnspacing
import android.graphics.Paint;
import android.graphics.Rect;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
/**
* An ItemDecoration which will apply even horizontal padding to the right and left edges
* of items in a vertical grid, while keeping the size of each item the same.
*
* It even works when there are different types in each row, as long as each
* row only contains one view type and each view type always spans the same number of columns.
*
*/
public class ColumnItemDecoration extends RecyclerView.ItemDecoration {
// Horizontal padding
private final int padding;
public ColumnItemDecoration() {
// Set padding (from resources probably)
}
@Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
GridLayoutManager.LayoutParams layoutParams = (GridLayoutManager.LayoutParams) view.getLayoutParams();
GridLayoutManager gridLayoutManager = (GridLayoutManager) parent.getLayoutManager();
float spanSize = gridLayoutManager.getSpanSizeLookup().getSpanSize(position);
float totalSpanSize = gridLayoutManager.getSpanCount();
float n = totalSpanSize / spanSize; // num columns
float c = layoutParams.getSpanIndex() / spanSize; // column index
float leftPadding = padding * ((n - c) / n);
float rightPadding = padding * ((c + 1) / n);
outRect.left = (int) leftPadding;
outRect.right = (int) rightPadding;
}
}
@RicardoBelchior

This comment has been minimized.

Copy link

commented Jan 10, 2018

hi , can you please tell me what position would be, at line 31 ?
thanks!

@TooLazyy

This comment has been minimized.

Copy link

commented Mar 16, 2018

@RicardoBelchior
int position = parent.getChildViewHolder(view).getAdapterPosition();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.