Skip to content

Instantly share code, notes, and snippets.

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 abhimuktheeswarar/958ded39e78c6a9b748106c3b98ccaa0 to your computer and use it in GitHub Desktop.
Save abhimuktheeswarar/958ded39e78c6a9b748106c3b98ccaa0 to your computer and use it in GitHub Desktop.
RecyclerView's ItemDecorator to achieve equal spacing around the items when using a GridLayoutManager
import android.graphics.Rect;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
public class EqualSpacingGridItemDecorator extends RecyclerView.ItemDecoration {
private final int padding;
public EqualSpacingGridItemDecorator(int padding) {
this.padding = padding;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
GridLayoutManager.LayoutParams layoutParams = (GridLayoutManager.LayoutParams) view.getLayoutParams();
GridLayoutManager gridLayoutManager = (GridLayoutManager) parent.getLayoutManager();
float spanSize = layoutParams.getSpanSize();
float totalSpanSize = gridLayoutManager.getSpanCount();
float n = totalSpanSize / spanSize; // num columns
float c = layoutParams.getSpanIndex() / spanSize; // column index
float leftPadding = padding * ((n - c) / n);
float rightPadding = padding * ((c + 1) / n);
int position = parent.getChildAdapterPosition(view);
//Add top padding only to first row
if (position == 0 || position == 1) outRect.top = padding;
outRect.left = (int) leftPadding;
outRect.right = (int) rightPadding;
outRect.bottom = padding;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment