Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
RecyclerView decorator which adds spacing around each tile within a grid layout
/*
Decorator which adds spacing around the tiles in a Grid layout RecyclerView. Apply to a RecyclerView with:
SpacesItemDecoration decoration = new SpacesItemDecoration(16);
mRecyclerView.addItemDecoration(decoration);
Feel free to add any value you wish for SpacesItemDecoration. That value determines the amount of spacing.
Source: http://blog.grafixartist.com/pinterest-masonry-layout-staggered-grid/
*/
public class SpacesItemDecoration extends RecyclerView.ItemDecoration {
private final int mSpace;
public SpacesItemDecoration(int space) {
this.mSpace = space;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
outRect.left = mSpace;
outRect.right = mSpace;
outRect.bottom = mSpace;
// Add top margin only for the first item to avoid double space between items
if (parent.getChildAdapterPosition(view) == 0)
outRect.top = mSpace;
}
}
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.