Recycler View With Android DataBinding

In I/O 2015, Google announced a data binding library for Android. With Data Binding, you create an ongoing link between an element in the user interface and a value. Data Binding is the process that establishes a connection between the Application UI and business logic.

In this post, we will learn how to integrate RecyclerView with Android Data Binding.

Step 1

Enable Data Binding in your module level gradle. Here is how your build.gradle should look.
  1. apply plugin: 'com.android.application'  
  2. android {  
  3.     compileSdkVersion 24  
  4.     buildToolsVersion "23.0.3"  
  5.     defaultConfig {  
  6.         applicationId "com.androidgig.recyclerviewbinding"  
  7.         minSdkVersion 15  
  8.         targetSdkVersion 24  
  9.         versionCode 1  
  10.         versionName "1.0"  
  11.         dataBinding {  
  12.             enabled true  
  13.         }  
  14.     }  
  15.     buildTypes {  
  16.         release {  
  17.             minifyEnabled false  
  18.             proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'  
  19.         }  
  20.     }  
  21. }  
  22. dependencies {  
  23.     compile fileTree(dir: 'libs', include: ['*.jar'])  
  24.     compile 'com.android.support:appcompat-v7:23.4.0'  
  25.     compile 'com.android.support:recyclerview-v7:23.4.0'  
  26.     compile 'com.squareup.picasso:picasso:2.5.2'  
  27. }  
Step 2

Create POJO/Model class called User with 3 parameters i.e. name, profile_image & age.
  1. public class User {  
  2.     private String name, profile_image;  
  3.     private int age;  
  4.     public User(String name, String profile_image, int age) {  
  5.         this.name = name;  
  6.         this.profile_image = profile_image;  
  7.         this.age = age;  
  8.     }  
  9.     public String getName() {  
  10.         return name;  
  11.     }  
  12.     public void setName(String name) {  
  13.         this.name = name;  
  14.     }  
  15.     public String getProfile_image() {  
  16.         return profile_image;  
  17.     }  
  18.     public void setProfile_image(String profile_image) {  
  19.         this.profile_image = profile_image;  
  20.     }  
  21.     public int getAge() {  
  22.         return age;  
  23.     }  
  24.     public void setAge(int age) {  
  25.         this.age = age;  
  26.     }  
  27. }  
Step 3

Create a layout for Recycler list items
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <layout xmlns:android="http://schemas.android.com/apk/res/android" 
  3.         xmlns:app="http://schemas.android.com/apk/res-auto" 
  4.         xmlns:tools="http://schemas.android.com/tools">  
  5.   
  6.     <data>  
  7.   
  8.         <variable  
  9.             name="user"  
  10.             type="com.androidgig.recyclerviewbinding.User" />  
  11.   
  12.     </data>  
  13.   
  14.     <LinearLayout android:layout_width="match_parent" 
  15.                   android:layout_height="wrap_content" 
  16.                   android:orientation="horizontal">  
  17.   
  18.         <LinearLayout android:layout_width="match_parent" 
  19.                       android:layout_height="wrap_content" 
  20.                       android:layout_margin="5dp" 
  21.                       android:background="@drawable/round_corner_view" 
  22.                       android:orientation="horizontal" 
  23.                       android:padding="10dp">  
  24.   
  25.             <ImageView android:layout_width="50dp" 
  26.                        android:layout_height="50dp" 
  27.                        tools:src="@mipmap/ic_launcher" 
  28.                        app:url="@{user.profile_image}" />  
  29.   
  30.             <LinearLayout android:layout_width="match_parent" 
  31.                           android:layout_height="wrap_content" 
  32.                           android:layout_gravity="center_vertical" 
  33.                           android:layout_marginLeft="10dp" 
  34.                           android:orientation="vertical">  
  35.   
  36.                 <TextView android:layout_width="wrap_content" 
  37.                           android:layout_height="wrap_content" 
  38.                           android:text="@{user.name}" 
  39.                           android:textAppearance="?android:attr/textAppearanceMedium" 
  40.                           android:textColor="@android:color/black" 
  41.                           tools:text="Name" />  
  42.   
  43.                 <TextView android:layout_width="wrap_content" 
  44.                           android:layout_height="wrap_content" 
  45.                           android:text="@{`` + user.age}" 
  46.                           android:textColor="@android:color/black" 
  47.                           tools:text="Age" />  
  48.   
  49.             </LinearLayout>  
  50.         </LinearLayout>  
  51.     </LinearLayout>  
  52. </layout>  
Here, the user will be model class reference variable. You can have any number of variables, as you need. <layout> will contain your model class information,  using which you will notify your controls about the value that they are going to show.

Step 4

Create an adapter for RecyclerView called UserAdapter.
  1. public class UserAdapter extends RecyclerView.Adapter<UserAdapter.ViewHolder> {  
  2.     private ArrayList<User> list;  
  3.     public UserAdapter(ArrayList<User> list) {  
  4.         this.list = list;  
  5.     }  
  6.     @Override  
  7.     public UserAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {  
  8.         View statusContainer = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_item, parent, false);  
  9.         return new UserAdapter.ViewHolder(statusContainer);  
  10.     }  
  11.   
  12.     @Override  
  13.     public void onBindViewHolder(ViewHolder holder, int position) {  
  14.         User status = list.get(position);  
  15.         holder.bindUser(status);  
  16.     }  
  17.   
  18.     @Override  
  19.     public int getItemCount() {  
  20.         return list.size();  
  21.     }  
  22.   
  23.     class ViewHolder extends RecyclerView.ViewHolder {  
  24.   
  25.         private RecyclerItemBinding binding;  
  26.         public ViewHolder(View itemView) {  
  27.             super(itemView);  
  28.             binding = DataBindingUtil.bind(itemView);  
  29.         }  
  30.   
  31.         public void bindUser(User user) {  
  32.             binding.setUser(user);  
  33.         }  
  34.     }  
  35. }  
Here

binding = DataBindingUtil.bind(itemView); will create binding for your recycler_item layout and return view.

binding.setUser(user);
will set the user data to recycler items.

Step 5

Write XML code for your activity/fragment layout.
  1. <layout xmlns:android="http://schemas.android.com/apk/res/android" 
  2.         xmlns:app="http://schemas.android.com/apk/res-auto">  
  3.   
  4.     <RelativeLayout android:layout_width="match_parent" 
  5.                     android:layout_height="match_parent">  
  6.         <android.support.v7.widget.RecyclerView android:id="@+id/recycler" 
  7.                      android:layout_width="match_parent" 
  8.                      android:layout_height="wrap_content" 
  9.                      app:layoutManager="android.support.v7.widget.LinearLayoutManager" />  
  10.     </RelativeLayout>  
  11. </layout>  
Step 6

Write your code in the activity/fragment to attach adapter to RecyclerView.
  1. public class MainActivity extends AppCompatActivity {  
  2.     private ActivityMainBinding binding;  
  3.     private ArrayList<User> userList = new ArrayList<>();  
  4.     private UserAdapter adapter;  
  5.     @Override  
  6.     protected void onCreate(Bundle savedInstanceState) {  
  7.         super.onCreate(savedInstanceState);  
  8.         binding = DataBindingUtil.setContentView(this, R.layout.activity_main);  
  9.         fillData();  
  10.         adapter = new UserAdapter(userList);  
  11.         binding.recycler.setAdapter(adapter);  
  12.     }  
  13.     private void fillData() {  
  14.         userList.add(new User("Ravi""https://pbs.twimg.com/profile_images/446522135721164800/pdVA44as.jpeg", 26));  
  15.         userList.add(new User("Ritesh""", 30));  
  16.         userList.add(new User("Naman""", 20));  
  17.     }  
  18.     @BindingAdapter({  
  19.         "bind:url"  
  20.     })  
  21.     public static void setImage(ImageView imageView, String url) {  
  22.         if (url != null & amp; & amp; url.trim().length() & gt; 0) {  
  23.             Picasso.with(imageView.getContext()).load(url).error(R.mipmap.ic_launcher).into(imageView);  
  24.         } else  
  25.             imageView.setImageResource(R.mipmap.ic_launcher);  
  26.     }  
  27. }  
Output

Output

This article was originally posted on AndroidGig.com.