Skip to content

Instantly share code, notes, and snippets.

@roschlau
Created September 7, 2016 19:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save roschlau/8ca3012bac7955d20d79bd78ee4ec670 to your computer and use it in GitHub Desktop.
Save roschlau/8ca3012bac7955d20d79bd78ee4ec670 to your computer and use it in GitHub Desktop.
An ItemDecoration that assigns even spacing to a grid of items, with the spacing between the items the same size as the outer spacing of the grid.
import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import android.view.View;
public class GridSpacingDecoration extends RecyclerView.ItemDecoration {
private int cols;
private int spacing;
public GridSpacingDecoration(int cols, int spacing) {
this.cols = cols;
this.spacing = spacing;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
int position = parent.getChildLayoutPosition(view);
outRect.bottom = spacing;
if (position <= cols-1) {
outRect.top = spacing;
} else {
outRect.top = 0;
}
outRect.left = spacing;
outRect.right = spacing;
if (position % cols == 0) {
outRect.right /= 2;
} else if(position % cols == cols - 1) {
outRect.left /= 2;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment