Skip to content

Instantly share code, notes, and snippets.

@zizibaloob
Created December 12, 2017 18:16
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zizibaloob/0c6be3e1318257950507e9c614c8aa70 to your computer and use it in GitHub Desktop.
Save zizibaloob/0c6be3e1318257950507e9c614c8aa70 to your computer and use it in GitHub Desktop.
Simple divider item decoration that also draws a divider on top of the first item
public class MyItemDecoration extends RecyclerView.ItemDecoration {
private static final int[] ATTRS = new int[]{ android.R.attr.listDivider };
private Drawable mDivider;
public MyItemDecoration(Context context) {
TypedArray a = context.obtainStyledAttributes(ATTRS);
mDivider = a.getDrawable(0);
a.recycle();
}
@Override
public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
int left = 0;
int right = parent.getWidth();
int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
View child = parent.getChildAt(i);
int position = parent.getChildLayoutPosition(child);
int bottom = child.getBottom();
int top = bottom - mDivider.getIntrinsicHeight();
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
if (position == 0) {
bottom = child.getTop();
top = bottom - mDivider.getIntrinsicHeight();
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
}
}
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
int height = mDivider.getIntrinsicHeight();
int position = parent.getChildLayoutPosition(view);
outRect.top = (position == 0) ? height : 0;
outRect.bottom = height;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment