Recyclerview or Viewpager is one of the most common UI elements we use in our Android apps. Of course these also have adapters. (like this) Most projects have a separate folder dedicated to adapters. If you are tired of just writing adapters for different binding, you can write generic ListAdapter. Write once use more 🙂
Firstly, Why Generic ListAdapter?
It’s basically RecyclerView.Adapter + DiffUtil
Recyclerview.Adapter base class for presenting List data in a Recyclerview, including computing diffs between Lists on a background thread.
This class is a convenience wrapper around
AsyncListDifferthat implements Adapter common default behavior for item access and counting.
for more → ListAdapter – Google
We need an abstract class for implement ListAdapter and write boilerplate codes, a base viewholder and base itemCallback.
Now, we can implement abstract generic listadapter class:
We will get the layout ID from the parameter. And we will redirect on getItemViewType ().
Yess, it’s higher order function the most important point. Because we will perform binding with this function.
We wrote once and now let’s use it:
I define two different recyclerview. First for text and other for images. All I have to do is use the generic adapter with object declaration and implement bind function.
There is more code than what I have mentioned here. These are the codes and data required for a recyclerview item. Here is full code:
And that’s it. I hope it has been a useful article for you. If you have any feedback please contact me. (Linkedin, mail or with comment)