Divider in RecyclerView with ItemDecoration

12 Oct


device-2016-10-12-1614071. Create class

package com.nikshit.Utilities;

import android.view.View;

public class DividerItemDecoration extends RecyclerView.ItemDecoration{
    private Drawable mDivider;
    public DividerItemDecoration(Drawable divider) {
        mDivider = divider;

    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);

        if (parent.getChildAdapterPosition(view) == 0) {
        } = mDivider.getIntrinsicHeight();

    public void onDraw(Canvas canvas, RecyclerView parent, RecyclerView.State state) {
        int dividerLeft = parent.getPaddingLeft();
        int dividerRight = parent.getWidth() - parent.getPaddingRight();

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

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

            int dividerTop = child.getBottom() + params.bottomMargin;
            int dividerBottom = dividerTop + mDivider.getIntrinsicHeight();

            mDivider.setBounds(dividerLeft, dividerTop, dividerRight, dividerBottom);

2. Create divider.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="" >
    <size android:height=".5dip" />
    <solid android:color="@android:color/darker_gray" />


3. Add lines below where you have defined RecyclerView

  RecyclerView.ItemDecoration dividerItemDecoration = new DividerItemDecoration(getResources().getDrawable(R.drawable.divider));
Leave a comment

Posted by on October 12, 2016 in Android Source Code


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: