Using DataBinding like a pro to write generic Recyclerview adapter.
We all love developing android apps and all of them have one thing very common in them, the LIST, hardly we can find an app that does not have a list in it.
So as an Android developer we have to write lots of code that revolve around Recyclerview and its adapter, its same boring repetitive code that we write with just a few lines of differences here and there.
Oh god, Isn’t there anyone who could save us from this boring stuff?
Can’t we write a generic code that could be used across almost all lists in our application?
Yes finally god listened to us and gave us a very powerful library — DataBinding library.
If you look carefully only part of the adapter that differs from another one is setting values for the view through models, that’s nothing but binding your view to ViewModel.
As we can easily handle binding with DataBinding library we no longer required to manually write the code to set values for a view like
textView.text = items[position].someText
That code would be automatically generated by the DataBinding library for us.
As the main part is generated by Databinding under the hood, we could easily write a generic Recyclerview adapter that could be used across the application, freeing us from writing boring repetitive stuff.
Show me the code
As we understood the basics lets deep dive into the code to see how could we achieve this.
First, We create ListItemViewModel class, its simple abstract class that each ViewModel should extend with.
This abstract class has 2 fields
- adapterPosition — that gives us row position.
- onListItemViewClickListener — that let us handle row item clicks
This click could be a row click or some button click from that row.
Next, we create a row layout file, In which we will have a variable named “listItemViewModel” this name could be anything you like
but it should be the same for all row layouts that you are planning to use with the generic adapter.
To alleviate the future pain rebuild the project now, so that the studio will generate “listItemViewModel” constant in the BR file.
Next is our GenericAdapter class
It’s pretty easy to understand
The real magic happens in bind() method of GenericViewHolder
here we are setting variable value using ViewDataBindings setVariable() method.
Do you remember the pain that I had talked about earlier if you don’t have that constant generated previously, we can’t use it over here and you will go nuts, hitting your head against the wall (Say thanks to me afterward)
In onBindViewHolder() method we set adapterPosition and onListItemViewClickListener on ItemViewModel
And finally this is how we use this adapter
That’s all to it If you find it useful don’t forget to give claps and share it with other people.
Please follow me on twitter narendrak3 to get latest stuff that I don’t publish on Medium.