ListAdapter with Custom View Components as Rows in Kotlin
A clean way to implement a self managed adapter that contains rows with multiple interactions
INTRODUCTION
You have a list of complex elements with many possible interactions, and you would like to implement its functionality as clean as possible.
In the example above we have a list of music tracks, where each row has four possible interactions. All possible options need to be connected with the Main View to be able to communicate with the View Model which, in case of any changes, can update and render the list of tracks properly on the screen.
Let’s have a look at how it can be done.
COMPONENTS INVOLVED
For this task 3 components are needed:
- RecyclerView — view component inside main layout, which will contain the list of music tracks.
- ListAdapter — component that will be the Adapter for RecyclerView
- Custom View for items of the list — view component which will be provided in the container of each row.
IMPLEMENTATION
First of all, xml layouts for each component will be provided:
- Main layout containing RecyclerView:
- Cell layout with custom view
- Custom view for a music track
Now it is time for the Kotlin code. Let’s start with implementation of each component:
- Music Track View with all possible interactions:
Custom component , extended from Coordinator Layout, where the specific layout is inflated with all necessary elements for possible user interactions. These are provided in the Interface, defined at the top.
- ListAdapter to connect RecyclerView and all Custom Views
This class extends ListAdapter and uses DIFF_UTIL_CALLBACK provided in our model to check and update the content if something has changed. Then we have a ViewHolder where Custom View is bound.
Some concepts:
ListAdapter —
RecyclerView.Adapter
base class for presenting List data in aRecyclerView
, including computing diffs between Lists on a background thread.DiffUtil — 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.
- Music List Activity, the context and container of RecyclerView:
In this class, set methods for the Adapter and RecyclerView are presented. Also, there is an Interface where we are going to handle all user interactions with elements in the list.
Conclusion
In summary, the goal was to make a list of custom components and prepare it for all possible interactions reducing lines of code. Doing it this way, the adapter implementation is short and clean. So, all that needs to be done is to just insert rows and forward all the data to Custom View. Then the Interface takes care of all interactions. Also, if the content has been changed, the adapter reacts automatically to it and renders the view properly without adding a single line of code, thanks to ListAdapter and DiffUtil. Overall, it is clean and easy to implement.