Reusability in Android (Kotlin) — List Adapter

Manav Tamboli
2 min readApr 3, 2021

In this article, we will shorten the code needed for creating a List Adapter for a Recycler View.

List Adapter is an Recycler View Adapter Extension, which provides a better performance than a normal Recycler View Adapter. If you have an understanding on how List Adapter works, then carry on. Otherwise, consider learning that first. See documentation.

Introduction

This is an usual implementation of the List Adapter :

List Adapter for a Todo List Recycler View

What Changes

On taking a look on the above implementation, it can noticed that the things which will keep changing from adapter to adapter will be:

  • the layout to inflate
  • the ViewHolder Class
  • the ViewHolder onBind() method

Objective

Creating an Adapter class (say AdapterX) and removing all the boilerplate code for any adapter.

Step 1

First of all, let’s create the class extending from ListAdapter. We will need these as parameters in our AdapterX Class to pass on to the ListAdapter:

  • Type Parameter T — type of the Lists this Adapter will receive, will be passed in the ListAdapter
  • Value Parameter DiffCallback — Diff Callback to pass in the ListAdapter

Note that, we also need to pass a Type Parameter of a ViewHolder class to the ListAdapter. But we will be creating a common ViewHolder Class for all adapters inheriting from AdapterX, removing the need to create a ViewHolder for each and every adapter.

Step 1

Step 2

Now, let’s implement onCreateViewHolder()

We will need a Layout Resource which is going to be inflated, and thus, we can take it as a constructor parameter in AdapterX.

Step 2

Step 3

And now, the onBindViewHolder()

As we know, the onBind functionality can change from adapter to adapter, we will create an abstract Extension Method for ViewHolder, and let the inherited adapter implement it.

Step 3

Usage

The AdapterX is ready to use now. Let’s take a look at the usage.

Usage

That’s the same adapter we implemented at the start of the article. Just see the difference. Using AdapterX will boost your production speed and code maintainability easier.

Limitations

  • We cannot do any view initializations when the ViewHolder is created, as we just have a common and simple ViewHolder Class.

Solution — There is no need for it anyways if we use View / Data Binding as all the views will be initialized when inflated. I’ll be posting articles about List Adapter + View / Data Binding Soon.

  • This will only work for adapters with only 1 Item View Types.

Solution — For multiple item view types, there is pretty much no reusability we can achieve.

EndNotes

The AdapterX covers the usual implementation of List Adapter, but you can always modify it to meet your requirements.

--

--