Reusability in Android (Kotlin) — List Adapter

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

List Adapter for a Todo List Recycler View

What Changes

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

Objective

Step 1

  • 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

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

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

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

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

19 years old self taught android developer.