ExpandableListView from RecyclerView
Google introduced RecyclerView to support library, which is a view-holder aware implementation of collection view. The children views can be positioned with LayoutManagers, and it comes with some builtin layout managers such as LinearLayoutManager supporting horizontal and vertical positioning, Grid, StaggeredGrid etc. The RecyclerView adapter provides some built-in animations for child view insertion, deletion and also supports transitions for rearrangement of views. Also you can handle different types of views in a RecyclerView, and it is easy to implement and use.

Since the RecyclerView supports different types of views, we can make use of this feature to implement the Expandable list view. Since it support animations, we can make use of them to animate the expand/collapse events. Unlike ExpandableListView, we can fully customise the textsize, color, and drawables to indicate whether the listview is expanded or not. And we can add header and footer, that also scrolls with the listview.

A RecyclerView can be implemented in three steps. Start from creating a viewholder, then create the adapter, and finally set the adapter to recycler view with appropriate layout managers.

So how does it work?


The implementation of ExpandableListView using RecyclerView is briefly described as follows. The list model has an additional parameter "type" that identifies whether the item is a header or child. By checking this parameter, the adapter inflates view and viewholder corresponding to the type. If the type is HEADER, it will inflate the layout of header item, that contains a TextView and a ImageView for indicating whether the child tree is expanded or not. For CHILD type, a TextView is created and since it doesn't contains any child components, an empty ViewHolder is created. The indicator ImageView has an OnClickListener that finds it's children and hides/reveals them. When the children is shown or hidden, notifyItemRangeInserted() and notifyItemRangeRemoved() methods gives a fade animation to the children.

The advantage of RecyclerView is that it doesn't have onItemClickListener, so the click events will be directly supplied to the child. So the header indicator ImageView can correctly handle the click events.

Check this: Demo Project