Add ItemDecoration for the RecyclerView Android

 We have used RecyclerView for showing the list of items. By default, I don't see the line that separating each items. 

That why, if i want to add the line blow item we show do the below step:
  1. Create CustomDividerItemDecoration.java
  2. Create line_divider.xml
  3. Add CustomDividerItemDecoration.java into MainActivity.java
Create CustomDividerItemDecoration.java 
public class CustomDividerItemDecoration extends RecyclerView.ItemDecoration {
    private Drawable mDivider;

    public CustomDividerItemDecoration(Context context){
        //mDivider = context.getResources()
        //              .getDrawable(R.drawable.line_divider); //deprecated
        mDivider = ContextCompat.getDrawable(context, R.drawable.line_divider);
    }

    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
        super.onDraw(c, parent, state);
        int left = parent.getPaddingLeft();
        int right = parent.getWidth() - parent.getPaddingRight();

        int childCount = parent.getChildCount();
        for(int i = 0; i < childCount; i++){
            View child = parent.getChildAt(i);

            RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();

            int top = child.getBottom() + params.bottomMargin;
            int bottom = top + mDivider.getIntrinsicHeight();

            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }
}
Create line_divider.xml
<?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <size
        android:width="1dp"
        android:height="1dp"/>
    <solid android:color="#ff0000"/>
</shape>
Add CustomDividerItemDecoration.java into MainActivity.java
mRecyclerView.addItemDecoration(new CustomDividerItemDecoration(this));
Output

 

Comments