Skip to content

Instantly share code, notes, and snippets.

@nesquena
Last active July 29, 2019 06:45
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nesquena/db922669798eba3e3661 to your computer and use it in GitHub Desktop.
Save nesquena/db922669798eba3e3661 to your computer and use it in GitHub Desktop.
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