Kişisel web sayfamda yazılım, teknoloji ve genel hayat hakkında paylaşımlar yapmayı hedefliyorum.

Generic ListAdapter with Kotlin|Write Once Use More

generic listadapter

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 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 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.

Image for post
listadapter

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

Image for post
recyclerview

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)

Project:

https://github.com/mustafayigitt/AndroidLearningProjects/tree/master/GenericListAdapter

Linkedin:

Share

You may also like...

Bir cevap yazın

E-posta hesabınız yayımlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir