Created
December 12, 2017 18:16
-
-
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
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
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