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

Mustafa Yiğit
ProAndroidDev
Published in
2 min readOct 24, 2020

--

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 :)

Firstly, Why 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 AsyncListDiffer that implements Adapter common default behavior for item access and counting.

for more → ListAdapter - Google

Let’s Start

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.

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.

Here is full code:

And result:

And that’s it. I hope it has been a useful article for you. If you have any feedback please contact me.

Project:

Linkedin:

--

--