Skip to content

Instantly share code, notes, and snippets.

@vincetreur
Created December 30, 2015 12:13
Show Gist options
  • Save vincetreur/4623110107c07c44b390 to your computer and use it in GitHub Desktop.
Save vincetreur/4623110107c07c44b390 to your computer and use it in GitHub Desktop.
A RecyclerView.ItemDecoration that adds 8 dp padding to the top of the first and bottom of the last item in a list (or RecyclerView in this case).
import android.content.Context;
import android.graphics.Rect;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;
/**
* Adds 8dp padding to the top of the first and the bottom of the last item in the list,
* as specified in https://www.google.com/design/spec/components/lists.html#lists-specs
*/
public class ListPaddingDecoration extends RecyclerView.ItemDecoration {
private final static int PADDING_IN_DIPS = 8;
private final int mPadding;
public ListPaddingDecoration(@NonNull Context context) {
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
mPadding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, PADDING_IN_DIPS, metrics);
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
final int itemPosition = parent.getChildAdapterPosition(view);
if (itemPosition == RecyclerView.NO_POSITION) {
return;
}
if (itemPosition == 0) {
outRect.top = mPadding;
}
final RecyclerView.Adapter adapter = parent.getAdapter();
if ((adapter != null) && (itemPosition == adapter.getItemCount() - 1)) {
outRect.bottom = mPadding;
}
}
}
@johndoe457
Copy link

You should rename it to ListMarginDecoration

I think the idea is that this margin creates the illusion of padding.

@DPYCB
Copy link

DPYCB commented Aug 31, 2021

If you want to set padding this way, you should use View instead of Rect inside getItemOffsets.
For example view.setPadding(0, mPadding, 0, 0) for top padding and view.setPadding(0, 0, 0, mPadding)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment