I’ve seen many people come up with complicated and bloated solutions to problems that can actually be solved with decorations quite easily. Generally speaking, by using decorations you can, without modifying any code in your adapter
add a Header / Footer View
add margins and separators
Easily added and reused with one line of code.
In this post, I want to explain the basic setup and use of item decorations by implementing a simple list separator.
Every decoration consists of 2 parts:
an (optional) additional required space for the view if you want to add paddings, margins or need to draw something around the view,
and the actual decoration itself that gets drawn on every view
The setup is easy. Just add your decorations along with the rest of the initial setup for your recyclerView.
I like decorations because they are easily reusable. You don’t have to adapt any of your existing code and most decorations will work with any recyclerView and content.
Enter the first Decoration
We want to draw a separator between all of our list elements, so we are going to request some extra space on the bottom of the views to prevent overdrawing and finally draw a line on the bottom.
Let’s start with the empty new decoration.
First we have to do the initial setup to enable some customization for the color and thickness of the separator.
Next we have to request some extra space beneath the view where we can draw without overdrawing. We do so by overwriting the base classes method and setting an offset at the bottom of each view.
If the LayoutManager handles the layout correctly (watch out if using some custom LayoutManagers) we can now draw the separator. Again, we just override the base classes method.
And we are done. If you did everything right, your list just got some fancy separators! Possible improvements might include
get a theme color resource as the default color
set a margin for the separator
dashed / dotted lines
Next up, how to add a header / footer to recyclerViews by using ItemDecorations.
A complete sample including a builder, the possibility to add margins or use a resource color can be located at GitHub.