This is an example of how it could have been done previously in the ListView
class, using the divider and dividerHeight parameters:
<ListView
android:id="@+id/activity_home_list_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="@android:color/transparent"
android:dividerHeight="8dp"/>
However, I don't see such possibility in the RecyclerView
class.
<android.support.v7.widget.RecyclerView
android:id="@+id/activity_home_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"/>
In that case, is it ok to define margins and/or add a custom divider view directly into a list item's layout or is there a better way to achieve my goal?
Best Answer
October 2016 Update
The version 25.0.0 of Android Support Library introduced the
DividerItemDecoration
class:Usage:
Previous answer
Some answers either use methods that have since become deprecated, or don't give a complete solution, so I tried to do a short, up-to-date wrap-up.
Unlike
ListView
, theRecyclerView
class doesn't have any divider-related parameters. Instead, you need to extendItemDecoration
, aRecyclerView
's inner class:Vertical
spacingItemDecoration
Extend
ItemDecoration
, add a custom constructor which takes spaceheight
as a parameter and override thegetItemOffsets()
method:If you don't want to insert space below the last item, add the following condition:
Note: you can also modify
outRect.top
,outRect.left
andoutRect.right
properties for the desired effect.Divider
ItemDecoration
Extend
ItemDecoration
and override theonDraw()
method:You can either call the first constructor that uses the default Android divider attributes, or the second one that uses your own drawable, for example drawable/divider.xml:
Note: if you want the divider to be drawn over your items, override the
onDrawOver()
method instead.Usage
To use your new class, add
VerticalSpaceItemDecoration
orDividerSpaceItemDecoration
toRecyclerView
, for example in your fragment'sonCreateView()
method:There's also Lucas Rocha's library which is supposed to simplify the item decoration process. I haven't tried it though.
Among its features are: