15

Following this answer I was able to get a divider between the items of a vertical RecyclerView. However, I also wanted to slightly indent the divider lines.

I was able to do it by hard coding in an INDENT value in the RecyclerView.ItemDecoration subclass.

int INDENT = 20;

@Override
public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) { 

    int left = parent.getPaddingLeft() + INDENT;
    int right = parent.getWidth() - parent.getPaddingRight() - INDENT;

    // ...

        divider.setBounds(left, top, right, bottom);

    // ...
} 

However, then I would have had to also mess with density independant pixels.

I finally found a solution similar to how it was done with ListView so I am sharing that as an answer below.

Community
  • 1
  • 1
Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393

1 Answers1

66

Use inset

drawable/my_divider.xml

<inset xmlns:android="http://schemas.android.com/apk/res/android"
       android:insetLeft="40dp"
       android:insetRight="40dp" >

    <shape>
        <size android:height="1dp"/>
        <solid android:color="@color/recyclerview_divider" />
    </shape>

</inset>

Using the constructor that takes a resource id as shown in this answer, we can supply the id of our custom divider xml file.

Update:

We can't add drawable in DividerItemDecoration constructor, we need to set drawable after created like in the example below

ItemDecoration dividerItemDecoration = new DividerItemDecoration(
    getActivity(), 
    RecyclerView.VERTICAL
)
dividerItemDecoration.setDrawable(drawable)
recyclerView.addItemDecoration(decorator);

Drawable drawable =

enter image description here

Thamilan S
  • 1,045
  • 3
  • 18
  • 30
Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
  • 3
    Thanks! Definitely beats all the other convoluted answers I've seen. – Bamerza Oct 10 '18 at 21:34
  • 4
    I get this error "Invalid orientation. It should be either HORIZONTAL or VERTICAL" when I do that – Stylishcoder Dec 25 '18 at 12:09
  • @ivange94, sounds like a problem with your layout manager. Check out this answer for the base code. https://stackoverflow.com/questions/40584424/simple-android-recyclerview-example/40584425#40584425 – Suragch Dec 25 '18 at 17:05
  • 12
    Of all the solutions I could find, this one is still superior 3 years later. A word of caution, the instantiation of the divider constructor today only allows the second parameter to be an orientation value, you have to set your custom Drawable after you instantiate via `dividerItemDecorationInstance.setDrawable(drawable)`. – Shadow Jan 31 '19 at 19:02