Reducing RecyclerView Adapter Boilerplate with Android Data Binding

Muthu Raj
AndroidPub
Published in
2 min readFeb 18, 2018

RecyclerView has it’s own way of creating views and binding data using ViewHolder pattern. In data binding, it is recommended that each view should contain separate viewModel class and the logic for that view should be contained inside that ViewModel class.

So using data binding, we already contain the logic of view in a separate class. Now it would be a wasteful boilerplate to implement all the onCreate and onBind methods of RecyclerView.Adapter class and extending RecyclerView.ViewHolder for every view type in every adapter. We can do better.

First of all, all your data binding variable names should be same (ex: viewModel).

Usually, we set the variable for the layout using DataBinding.set{{variableName}}(object). There is another less known method in the ViewDataBinding class(which is the base class for all generated data binding class) called setVariable which takes a BR field and the actual variable as parameters. For every data binding variable, a field in BR class is generated(just like for every drawable, layout, strings etc. a field is created in R.java).

Suppose if our variable name is viewModel, then instead of using setViewModel(viewModelInstance), we can say setVariable(BR.viewModel, viewModelInstance). We utilize this base class method to simplify our recyclerView adapter.

Here is the code for the RecyclerView Adapter which you need to extend from.

And this is the RecyclerViewHolder class.

The setVariable method returns a boolean which indicates whether the binding is successful or not. Why would it not be successful, you may ask. Usually because the BR field you specified is not the name you set in you xml. If it fails, our ViewModel would not be bind to the view and nothing will show on the UI. It is hard to debug what went wrong at this point, trust me. That’s why we throw an exception if the binding variable is mismatched (Fail Fast).

Also this supports multiple viewTypes by setting the viewType from layout id.

Now your actual implementation of RecyclerView Adapter would be like this.

Feedbacks are welcome. Happy coding :)

--

--