Most Generic Adapter Ever Made!

Sandip Savaliya
2 min readJan 8, 2020

In Android, it's very common to show the data in the list. Usually, we do that using ListView or RecyclerView.

If a project has 10 different lists with ten different items then usually people end up in creating 10 different adapters. Let's solve this problem by creating a generic adapter and not writing 10 different adapters for this.

Note: We are using Kotlin with MVVM Databinding for implementing it.

As shown in below snippet lets create a Generic ViewHolder to make our View’s Dynamic.

We need to define an onCreateViewHolder() method through which we can generate a dynamic Viewholder based on Layout Resource. For that, we have to create a BaseModel which will have Layout Resource id as a Constructor parameter.

Now, the onCreateViewHolder() method will generate a GenericViewHolder which will be returned by kotlin Callback while binding view.

Again, We have used viewType as a resource id to be inflated. So, now we will need to return that viewType based on the following method.

That’s it, we have created a Generic Adapter.

We are done with Adapter, Let’s see How to use it in real practice. For that, we need a Model object to be iterated which should be extended by BaseModel, Here use layout id as a Resource Id parameter which will be used in an adapter.

Now let's continue with assigning an adapter with RecyclerView

And we’re done, A Pure generic adapter which can be used to iterate any type of models having different layout Ids and different Data( It must extend BaseModel though).

The beauty of this adapter is you can create a multi-view type list very easily. Consider the example above your list has different objects, based on the object type we return different layouts, and based on different layout we bind different models.

Visit my portfolio here.

That’s it folks, please comment below if you have any questions.



Sandip Savaliya

A Programmer with huge IT encounter & Programming skills (Data-Structures & Algorithms), Analytical & Innovative critical thinking.