In this article, we will shorten the code needed for creating a List Adapter for a Recycler View.
List Adapter is an Recycler View Adapter Extension, which provides a better performance than a normal Recycler View Adapter. If you have an understanding on how List Adapter works, then carry on. Otherwise, consider learning that first. See documentation.
This is an usual implementation of the List Adapter :
On taking a look on the above implementation, it can noticed that the things which will keep changing from adapter to adapter will be:
- the layout to inflate
- the ViewHolder Class
- the ViewHolder onBind() method
Creating an Adapter class (say AdapterX) and removing all the boilerplate code for any adapter.
First of all, let’s create the class extending from
ListAdapter. We will need these as parameters in our
AdapterX Class to pass on to the
- Type Parameter T — type of the Lists this Adapter will receive, will be passed in the
- Value Parameter DiffCallback — Diff Callback to pass in the
Note that, we also need to pass a Type Parameter of a ViewHolder class to the
ListAdapter. But we will be creating a common ViewHolder Class for all adapters inheriting from
AdapterX, removing the need to create a ViewHolder for each and every adapter.
Now, let’s implement
We will need a Layout Resource which is going to be inflated, and thus, we can take it as a constructor parameter in
And now, the
As we know, the onBind functionality can change from adapter to adapter, we will create an abstract Extension Method for
ViewHolder, and let the inherited adapter implement it.
AdapterX is ready to use now. Let’s take a look at the usage.
That’s the same adapter we implemented at the start of the article. Just see the difference. Using
AdapterX will boost your production speed and code maintainability easier.
- We cannot do any view initializations when the ViewHolder is created, as we just have a common and simple ViewHolder Class.
Solution — There is no need for it anyways if we use View / Data Binding as all the views will be initialized when inflated. I’ll be posting articles about List Adapter + View / Data Binding Soon.
- This will only work for adapters with only 1 Item View Types.
Solution — For multiple item view types, there is pretty much no reusability we can achieve.
The AdapterX covers the usual implementation of List Adapter, but you can always modify it to meet your requirements.