Skip to content

Instantly share code, notes, and snippets.

@AKiniyalocts
Created December 8, 2016 21:00
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AKiniyalocts/5a00d66f03f1c3393c1302bea73749b2 to your computer and use it in GitHub Desktop.
Save AKiniyalocts/5a00d66f03f1c3393c1302bea73749b2 to your computer and use it in GitHub Desktop.
Quick way to add padding to first and last item in recyclerview via decorators
package com.batterii.mobile.ui.component.decorators;
import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import android.view.View;
/**
* Created by anthonykiniyalocts on 12/8/16.
*
* Quick way to add padding to first and last item in recyclerview via decorators
*/
public class EdgeDecorator extends RecyclerView.ItemDecoration {
private final int edgePadding;
/**
* EdgeDecorator
* @param edgePadding padding set on the left side of the first item and the right side of the last item
*/
public EdgeDecorator(int edgePadding) {
this.edgePadding = edgePadding;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
super.getItemOffsets(outRect, view, parent, state);
int itemCount = state.getItemCount();
final int itemPosition = parent.getChildAdapterPosition(view);
// no position, leave it alone
if (itemPosition == RecyclerView.NO_POSITION) {
return;
}
// first item
if (itemPosition == 0) {
outRect.set(edgePadding, view.getPaddingTop(), view.getPaddingRight(), view.getPaddingBottom());
}
// last item
else if (itemCount > 0 && itemPosition == itemCount - 1) {
outRect.set(view.getPaddingLeft(), view.getPaddingTop(), edgePadding, view.getPaddingBottom());
}
// every other item
else {
outRect.set(view.getPaddingLeft(), view.getPaddingTop(), view.getPaddingRight(), view.getPaddingBottom());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment