Month: February 2018

Adding Divider to your Recycler View !

When we add items to a recycler view, there is no default separation between these. In order to make your list of items look more presentable and a good distinction, below I demonstrate how to add a divider in between the recycler view items with a linear layout.

Note : For people new to Recycler view, I will write my next blog post explaining all about them and how to use them to create a dynamic list.

Here assuming the recycler view is already added to the code, we just use DividerItemDecoration to add the default dividers between items, in the following way:

DividerItemDecoration decoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
recyclerView.addItemDecoration(decoration);

The constructor for the DividerItemDecoration takes two parameters, context and the orientation of the recycler view.

If we want to add a custom divider instead of the default one, create a Drawable divider_item xml as follows, specifying the height and the attributes of the divider:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <size
        android:width="1dp"
        android:height="1.5dp" />
    <solid android:color="@android:color/holo_red_dark" />
</shape>

And set this drawable for the DividerItemDecoration shown above in the following manner:

decoration.setDrawable(ContextCompat.getDrawable(this, R.drawable.divider_item));

Sample code is available on github.