Demo
Code
View the source and demo project on GitHub.
How it Works
This is an implementation of the recycler view adapter that provides a re-usable way to implement expandable and collapsible header items. The user clicks a header item, which expands the arrow in the right side and “expands” the section by dynamically inserting the items belonging to that header.
I implemented this by defining a base class, ExpandableRecyclerAdapter
. It is a generic class that takes one parameters, the list item type:
All the work is done in the adapter class. You do not need to subclass or alter the Reycler View itself.
When the user clicks a header item, the base adapter will automatically handle the click event and expand or collapse the section by inserting or removing items using the fine-grained notify methods available on the adapter.
Usage
To use in your app,
- Derive your adapter class from
ExpandableRecyclerAdapter
- Define a
ListItem
class that derives from the base adapter’s ListItem and populate your list with those items viasetItems
- Define the layouts for the header and list items, inflate those in your
onCreateViewHolder
method. ViewHolders must derive from the base adapter ViewHolder. - In
onBindViewHolder
make sure youbind
the header item, as this will allow it to manage the arrow properly.
There are some nuances to working with the adapter, so be sure to check the example code on GitHub and try it out!