Generic ListAdapter with Kotlin | Write Once Use More | Recyclerview & Viewpager

Recyclerview or Viewpager is one of the most common UI elements we use in our Android apps. Of course these also have adapters. 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 🙂

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 AsyncListDiffer that 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 list adapter 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.