Skip to content

Instantly share code, notes, and snippets.

@karllindmark
Last active September 19, 2015 08:17
Show Gist options
  • Save karllindmark/276491e546979787f563 to your computer and use it in GitHub Desktop.
Save karllindmark/276491e546979787f563 to your computer and use it in GitHub Desktop.
A (quick & dirty) grid item spacing decorator for the RecyclerView that enables us to have some spacing around the items.
/* Derived from http://stackoverflow.com/a/27664023/1676363 */
public class GridItemSpacingDecorator extends RecyclerView.ItemDecoration {
private final int columnCount;
private final int spaceInPixels;
public GridItemSpacingDecorator(int columnCount, int spaceInPixels) {
this.columnCount = columnCount;
this.spaceInPixels = spaceInPixels;
}
public GridItemSpacingDecorator(int columnCount, int spaceInPixels, float densityMultiplier) {
this.columnCount = columnCount;
this.spaceInPixels = (int) (spaceInPixels * densityMultiplier);
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
// We always want to add right/bottom spaceInPixels
outRect.right = spaceInPixels;
outRect.bottom = spaceInPixels;
// Only add top margin for the first row
if (parent.getChildPosition(view) < columnCount) {
outRect.top = spaceInPixels;
}
// Only add left margin for the left-most items
if (parent.getChildPosition(view) % columnCount == 0) {
outRect.left = spaceInPixels;
}
}
}
@ataulm
Copy link

ataulm commented Apr 27, 2015

Hey, this isn't just between the items, but around every item right?

AFAIK, to replicate the behaviour of GridView's horizontalSpacing and verticalSpacing, you'd need to:

  • not include offset for items along the left, top, right and bottom edges of the RecyclerView, considering that items could have different spans
  • consider that increasing the offset for each item reduces the available layout space for each item, so to maintain uniform dimensions would need to weight the offsets if they weren't equal on each side

I think Lucas Rocha's done it on his TwoWayView library, but would be good to make one that can be used with the regular RecyclerView and GridLayoutManager :( I'm working on it, but difficult to get my head around such that it works for all cases

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment