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)); | |
... | |
} |