Skip to content

Instantly share code, notes, and snippets.

@lisawray
Last active May 29, 2023 21:11
Show Gist options
  • Save lisawray/bff18199864b120c495971177a89115b to your computer and use it in GitHub Desktop.
Save lisawray/bff18199864b120c495971177a89115b to your computer and use it in GitHub Desktop.
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
Copy link

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

@TooLazyy
Copy link

TooLazyy 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