Display RecyclerView sections like Android Lollipop contacts application
One of my projects require to display sticky headers like Android Contacts app do on Android Lollipop.
After some time of investigation i’ve found simple way to archive this looks and feel. Now its quite naive and requires a lot of improvement, but its quite usable.
I’ll start implementation from describing how to get sections index for loaded list of contacts.
Here is simple model class to store contact information fetched from ContentProvider.
Its quite simple, as everything we need to showcast is contact name.
To build section index we need sort our list of contacts by name alphabetically. I’ll skip this part, as its quite straight forward, if you want go deep, checkout github link down this post.
When we have our sorted contacts list, we can fill section index
In result we got some variables that can be used for section headers
mMapIndex - map of contact name uppercased first character and index of first contact in list
mSectionList - list of all sections sorter alphabetically
Now, when we have sections, we can start displaying contacts in Views. Item layout has TextView to display contact name, and section title to display section when required.
To detect if we need to display section, we have mMapIndex HashMap, if list position we want to bind to viewholder equals to section position we display section title TextView, or hide it otherwise.
In simplest case ViewHolder gets such code:
Binding ViewHolder is also straightforward:
Now we can load and display contact list with section titles displayed on the first section item. Now we need to handle RecyclerView scrolling to get sticky headers behavior.
I will not put all code for this logic here, you can find it in GitHub project listed in the end of this article.
The main logic is to have TextView with the same style as section title item in item list and show/hide appropriate TextView in the item and animate TextView in the Activity.
This solution is not fully completed, and may have some issues under some unexpected circumstances, but as its opensourced you can easily create issue or submit your pull request.