A clean way to do Multi ViewType RecyclerViews on Android.
Sealed Classes to the rescue!
Hey 👋🏻
Let’s be honest about it, Recycler Views on Android are not the most friendliest things to work with, specially when your design includes a list with multiple view types. In this article, I will share a clean way to utilise the power of Kotlin’s Sealed Classes to implement a Multi ViewType Recycler View.
You can see one example in the image above, the data for such a design is generally possessed in a 2D list, where we have one list of sections and then another list of items inside it, just like the CarData example shown below. This data could be stored locally or coming from a remote source.
Now here is the most important thing, this data can not be directly pushed to the UI because the Recycler View understands data in a 1D manner. It can show a list of items but not a nested list. So we need to convert this 2D list to a 1D list and Sealed Classes are a great way to do that.
Implementation
We need one Sealed Class for the representing the data in the new 1D form which can be directly fed as a list to the Recycler View, just like CarListData shown in the snipper below (full codebase linked at the end) which also directly provides a method to convert from the CarData.
We need another Sealed Class for the View Holders, since we have 2 different kind of View Types here, we will require 2 ViewHolder classes under one Sealed Class, just like CarListViewHolder shown below. Each one of the ViewHolders respond to a data class in the Sealed Class CardListData.
Now at the end we will bind (pun intended 😛) this all up with Recycler View’s Adapter. We will need an Enum for the ViewTypes like CarListViewType. The adapter will use the Sealed Class CardListViewHolder and will receive a list of the CarListData and the ViewType for the item on the current position will be decided based on its data type.
Now in the onCreate method, based on the ViewType we will inflate the view and return the appropriate ViewHolder. In the onBind method we will check the Data Type for the list item on the current position, this will tell us which ViewHolder should be used for this item and appropriately cast it.
You made it
This was a short tutorial on how I keep my Recycler Views neat and tidy in case it involves multiple View Types.
If you are still reading here’s a virtual high five 👋🏻. If you would like to suggest an improvement or just try out this approach you can access the code here.
I will see you in the next one, Ciao!
