UPDATE(March 2021)
ExpandableListView
will not provide the performance and memory benefits provided by RecyclerView. Hence I wrote my own ultra lightweight library that consists of a custom recycler adapter and custom recycler view(only required if grid layout is required) on top on inbuilt RecyclerViewAdapter
and RecyclerView
respectively. The adapter exposes some functions similar to how iOS table view works, hence making it super easy to implement sectioned recycler view while sticking to your own code design. Detailed instructions can be found in the project github page linked below. The dependency is available from maven central.
Sectioned RecyclerView
implementation 'com.github.harikrishnant1991:sectioned-recyclerview:1.0.0'
Original Answer
Alternative to using any third party library or using custom logic to add header to RecyclerView
, there is a much simpler solution using Android SDK. You can simply use ExpandableListView
. You might be thinking that it makes the list collapsible, but there is a very simple thing which you can do to avoid the same. In the adapter class for ExpandableListView
, in the getGroupView
method, simply add the following line:
(parent as ExpandableListView).expandGroup(groupPosition)
The method would look something like this:
override fun getGroupView(groupPosition: Int, isExpanded: Boolean, convertView: View?, parent: ViewGroup?): View {
var view = convertView
if (convertView == null) {
val layoutInflater = context
.getSystemService(LAYOUT_INFLATER_SERVICE) as LayoutInflater
view = layoutInflater.inflate(R.layout.group_view, null)
}
/*
Code to populate your data
*/
// The following code will expand the group whenever the group view is inflated
(parent as ExpandableListView).expandGroup(groupPosition)
return view
}
This works simply due to the way how ExpandableListView
adapter works. Whenever you try to collapse a group header, it calls the getGroupView
method(so that you can inflate a different view for expanded/collapsed state). But you are expanding the group in that method, hence the view never actually collapses, effectively giving you a sectioned list appearance.
Expect for the one line mentioned above, all other part of the same is exactly as you would do with a normal ExpandableListView
, hence there is no additional bit of customisation you need to do.