The error is because you are telling the RecyclerView to draw your decoration number 2, without telling it what to draw number 1 and 0.
(It's implemented as an ArrayList of decorations to draw in order, and it's trying to insert your decoration at index 2 into an empty ArrayList - hence OutOfBounds!)
Edit: Here's a working example:
I've tested this code, and it works fine if you make the following changes:
1- Use the single parameter version of the method, the indexed version will give out of bounds as explained (you need to start indexing from 0).
r.addItemDecoration(new SpacesItemDecoration(10));
2- Use the following ItemDecoration class:
public class SpacesItemDecoration extends RecyclerView.ItemDecoration {
private int space;
public SpacesItemDecoration(int space) {
this.space = space;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
outRect.bottom = space;
}
}
This will give you space only at the bottom (for horizontal dividers).
3 - Change your RecyclerView layout so that the background colour of your RecyclerView is the colour you want the dividers to be:
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000"> # DIVIDER COLOUR
</android.support.v7.widget.RecyclerView>
4- Change your item layout so that the background of the root item is not transparent, and not the same colour as the RecyclerView (obviously)
<RelativeLayout
android:id="@+id/item_root"
android:background="#cc00cc"
android:layout_width="match_parent"
android:layout_height="wrap_content">
The reason nothing was showing before may have been because the RecyclerView background and the item background were the same, so the divider wasn't visible.
This method works with both Linear and Grid Layout Managers.
I hope this (finally!) helps :)