RecyclerView add divider lines only between some items

Issue

I want to add divider lines in my RecyclerView Layout. I already searched some time, but I can only find solutions that utilise RecyclerView.addItemDecoration, which adds the divider between all items. I could create a layout that has a single line and add that to the RecyclerView, but that doesn’t seem like an elegant solution to me.

Solution

You can write a custom RecyclerView.ItemDecoration and draw divider only where you need. And set it to RecyclerView using:

recyclerView.addItemDecoration(new YourItemDecoration());

This is the default DividerItemDecoration source code:
https://android.googlesource.com/platform/frameworks/support/+/refs/heads/master/v7/recyclerview/src/android/support/v7/widget/DividerItemDecoration.java

You can find the divider drawing logic in onDraw method, where it draws divider for all items. You have to change that part based on your needs to draw divider for some items only. getItemOffsets() method adds offset to the item to make space for the divider.

Answered By – Bob

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published