Basically what the title asks, what is the point of having item decorations in recycler views if you can achieve the same effect by editing the layout you are inflating in the recycler view.
Because you cannot always "achieve the same effect by editing the layout you are inflating in the recycler view" very easily.
This is particularly true if you want ListView
-style dividers that go between entries (say, in a vertical list). In that case, not every item has a divider -- either the first or the last does not. For simple cases, you could still handle that within the layouts themselves, by hiding a divider in the layout when it's the item that should not have a divider. However, if you:
allow users to reorder the items, or
you use something like SortedList
to keep items in a sorted order, or
you are dynamically adding and removing items
then trying to make sure that the dividers are handled correctly is a pain, because which items get and do not get the divider keep shifting.
The item decoration approach keeps the logic for drawing decorations independent of the items themselves, so changes in the mix of items does not affect the decoration process. It also makes it easier to:
implement standard item decoration patterns in a library
dynamically change decoration patterns on the fly, such as based on user preferences
Not every RecyclerView
will use item decorations. In particular, those using CardView
for the top-level layout for items probably skip item decorations, as the CardView
itself provides visual distinction and separation between items.
So, you do not have to use the item decoration approach, but it is available for cases where it simplifies how you set up your UI.
Well, handling stuff like dividers in the item layouts IS possible, but can be tricky and results in additional, useless code. The Decorator
, on the other hand, allows you to draw them easily, right into the Canvas
. You can also draw other things, like badges, highlights etc.
However, this is not the main reason. The true reason is the fact that RecyclerView
is not and should not be seen as a "cooler ListView
". It is so much more! :-)
Imagine you want to draw a Zuma-like structure of star-shaped items. You can do it easily with a RecyclerView
and a custom LayoutManager
. And if you want to add dividers to such a layout, it will be easier to draw directly onto the canvas, will it not?
RecyclerView
is, well, a recycler view, an abstract, top-level implementation for all recycling Views
(so ListView
, GridView
, StarShapedZumaSnakeView
etc.) :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With