Android Clean Adapter — This is how adapters should be

Johan Kovalsikoski
2 min readDec 29, 2020

Have you ever wrote an adapter with interactions and thought that you would like that logic in another place? Or it should be cleaner and easier to read? If so, this is the place to be. If not, keep reading and I am sure it will change your mind.

Here you can find the code before and after the adapter refactor.

The problem

The snippets below shows the first version of a RecyclerView Adapter with logic for clicking on add/remove buttons and it’s layout file.

The problem with this adapter is that the ViewHolder is holding values and some logic to add/remove/etc… It is bloated and can quickly become messy. However, soon we will solve this problem.

MainAdapter.kt — Before
Item.xml — Before
Application screen

The solution

The first thing to keep in mind is that all this logic should be handle in a class other than the Adapter. So the class below will create a Component and it will handle all the interactions and logic.

MainAdapterItem.kt — Refactor part #1

You will notice as you read the layout that was called item.xml now is main_adapter_item.xml and the new item.xml will be different, since it now just calls the custom Component we created.

Item.xml — Refactor part #2

And for the last part we have to update our old adapter to use his new layout.

MainAdapter.kt — Refactor part #3

Now the ViewHolder just handles what is really needed and the adapter is very clean!

Well that’s it! I hope you have enjoyed it and I may have taught you something useful. Now have good luck on your Android journey!

I want to thank Felipe Ferraz and Ozan Kalan for the help with the code and the writing! You guys rock!

--

--

Johan Kovalsikoski

As a writer, reader, programmer and gamer, I am constantly exploring and learning.