Photo by Thought Catalog on Unsplash

RecylerView List Adapter Template in Kotlin

Arif Khan
AndroidPub
Published in
3 min readJul 30, 2018

--

To start with let me explain, what is a file template?

A file template is a source file that already contains some code to get you started.

Writing recyclerview adapters is one of the most repetitive tasks in Android development and most of the business logic remains same for all adapters binding views and creating viewholders. As there is a rule in software development that if you are doing something manually for more than three times then it’s better to automate it. So I decided to write a RecyclerView template for Android Studio.

It helped me to generate a RecyclerView adapter in seconds with all the goodness of Diffutil, ListAdapter and kotlin, saving all the time in the universe.

DiffUtil is a utility class that can calculate the difference between two lists and output a list of update operations that converts the first list into the second one. It can be used to calculate updates for a RecyclerView Adapter.

ListAdapter is written on top of DiffUtil. If you use ListAdapter you won’t have to fully implement DiffUtil and you will automatically get nice animations when new items are added, removed or changed in the recyclerview. ListAdapter is added in support library version 27.1.0 and above.

RecyclerView ListAdapter Template

How to add this file template to Android Studio

Go to File New → Edit File Templates → Click on plus button → Give a name to your template and type Extension as kt as we are creating this template for kotlin. Copy the above template and paste it in the box and click on Apply.

How to use this file template

Go to the package where you want to write an adapter. Right-click → New → Select RecyclerView List Adapter. It will ask for some inputs -

Provide the name, model class and the item id for your adapter. Press ok and see the magic. Your adapter will be ready with few imports which you have to auto import manually.

Note: This template will generate a class “DiffCallback” inside the adapter. If you are going to use this template to generate multiple adapters then each DiffCallback class name should be unique.

How to use the generated adapter

If you have the list available then just writing a single line adapter.submitList(list) will do all the magic. Comparing the old list with the new one and showing animations if any data is updated, added or removed. The catch is that you have to always provide a new instance of the list instead of adding the new data in the same list.

Let’s see what this adapter can do for us

Sample demo after implementing the adapter

If you liked this article, please clap and feel free to leave a comment below.

You can find me on LinkedIn, Twitter and Github.

--

--