Created
September 7, 2016 19:40
-
-
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.
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
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