Last active
September 19, 2015 08:17
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey, this isn't just between the items, but around every item right?
AFAIK, to replicate the behaviour of GridView's
horizontalSpacing
andverticalSpacing
, you'd need to: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