In this tutorial, we’ll be discussing and implementing the RecyclerView Using Data Binding in our Android Application.

Android RecyclerView DataBinding

In order to know the basics of Android DataBinding, do visit this tutorial.

Data Binding significantly reduces the boilerplate code. Here, we’ll learn how to implement DataBinding with a RecyclerView which has the ViewHolder pattern.

Also, we’ll understand how Data Binding makes it easy to generalise the Adapter classes.

Finally, we’ll demonstrate how to directly pass the adapter object in the XML.

Getting Started

Add the following code in your app’s build.gradle:

Add the following dependency.

Project Structure

android-recyclerview-data-binding-project-structure

In the below application we’ll load the data in the adapter rows of the RecyclerView from the XML using the <data>. Also we’ll set the onClickListener methods in the layout rows itself.

Code

The code for the DataModel.java class is given below:

The code for the activity_main.xml layout is given below:

MainActivity.java

The layout for each row of the RecyclerView is defined in item_row.xml.

Inside the data tag, we pass two variables – a DataModel reference and a reference of the CustomClickListener interface whose method is called in the CardView.

The code for the CustomClickListener.java is defined below:

The code for the MyRecyclerViewAdapter.java class is given below:

In order to pass the data to the XML counterpart we bind it using itemRowBinding.setVariable(BR.model, obj);.

executePendingBindings() is important in order to execute the data binding immediately. Otherwise it can populate incorrect view.

Difference between setVariable() and setModel()setVariable() is used in generic circumstances when the type of the data is not known.

setModel() is auto-generated. We can use the following instead of holder.bind(dataModel);.

Passing the Adapter instance in RecyclerView XML Using Data Binding

Thanks to data binding we can further reduce the boilerplate code in our MainActivity.java by passing the adapter instance in the XML inside the android:adapter attribute as shown below:

activity_main.xml

In the MainActivity.java we can set the Adapter in the following way now:

So there’s no need to even initialize RecyclerView in the Activity class.

The output of the above application in action is given below:

android recyclerview data binding output

That brings an end to this tutorial. You can download the project from the link below.

By admin

Leave a Reply