Skip to content

Instantly share code, notes, and snippets.

@OrenBochman
Last active September 9, 2018 15:13
Show Gist options
  • Save OrenBochman/4a5a7c7b09c8fd1a0eca0072d39cfab7 to your computer and use it in GitHub Desktop.
Save OrenBochman/4a5a7c7b09c8fd1a0eca0072d39cfab7 to your computer and use it in GitHub Desktop.
Adding dividers to a RecyclerView

RecyclerView - Adding Dividers

How to add deviders between recyclerview items.

Based on the book Pro Android UI.

public class ItemDivider extends RecyclerView.ItemDecoration {
Private Drawable divider;
public ItemDivider(Context context) {
final TypedArray styledAttributes = context.obtainStyledAttributes(ATTRS);
divider = styledAttributes.getDrawable(0);
styledAttributes.recycle();
}
public ItemDivider(Context context, int resId) {
divider = ContextCompat.getDrawable(context, resId);
}
@Override
public void onDraw(Canvas canvas, RecyclerView parent, RecyclerView.State state) {
int left = parent.getPaddingLeft();
int right = parent.getWidth() - parent.getPaddingRight();
int count = parent.getChildCount();
for (int i = 0; i < count; i++) {
View child = parent.getChildAt(i);
RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
int top = child.getBottom() + params.bottomMargin;
int bottom = top + divider.getIntrinsicHeight();
divider.setBounds(left, top, right, bottom);
divider.draw(canvas);
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<size android:height="1dp" />
<solid android:color="@color/colorPrimaryDark" />
</shape>
onCreare(){
...
recyclerView.addItemDecoration(new ItemDivider(this, R.drawable.item_divider));
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment