Develop apps faster using Data Binding – Part 2

Google has been pushing updates to existing tools and making the life of android developers easier. They also have been releasing new libraries and APIs. “Data binding” is one of them. In this series, we are going to focus on some powerful features of it.

In our previous article, we learnt how to integrate Data Binding library and how to use it in layout file. In this tutorial, we are going to learn how to use it in RecyclerView.

How to use Data Binding with RecyclerView

Step 1

Create a Project and open main Gradle file of the project.

Main Gradle
Main Gradle

Add below two lines in your dependencies tag

dependencies {
    classpath 'com.android.tools.build:gradle:1.3.0'
    classpath 'com.android.databinding:dataBinder:1.+'
}

This will add a dependency to your project.

Step 2

Now open your module’s Gradle file. We require to add a plug-in to our project.

apply plugin: 'com.android.databinding'

Your whole Gradle file will look like this

apply plugin: 'com.android.application'
apply plugin: 'com.android.databinding'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "chintan.rathod.databindingdemo"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.0'
    compile 'com.android.support:recyclerview-v7:+'
    compile 'com.android.support:cardview-v7:22.0.0'
}

Step 3

Start a new Empty project. Create a class called User. Paste below code inside. This will create a class with two members called Name and Age

public class User  {

    public String displayName;
    public int age;

    public User(String displayName, int age){
        this.displayName = displayName;
        this.age = age;
    }
}

Step 4

Create a layout file and name it user_item.xml. Paste below code.

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto">

    <data>

        <variable
            name="user"
            type="chintan.rathod.databindingdemo.Model.User" />
    </data>

    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        card_view:cardCornerRadius="2dp"
        card_view:contentPadding="10dp">

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <LinearLayout
                android:orientation="horizontal"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <TextView
                    android:layout_width="100dp"
                    android:layout_height="wrap_content"
                    android:text="Name"
                    android:textSize="22sp" />

                <TextView
                    android:id="@+id/txtDisplayName"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@{user.displayName}"
                    android:textSize="22sp" />

            </LinearLayout>

            <LinearLayout
                android:orientation="horizontal"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <TextView
                    android:layout_width="100dp"
                    android:layout_height="wrap_content"
                    android:text="Age"
                    android:textSize="22sp" />

                <TextView
                    android:id="@+id/txtAge"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@{String.valueOf(user.age)}"
                    android:textSize="22sp" />
            </LinearLayout>

        </LinearLayout>

    </android.support.v7.widget.CardView>
</layout>

Here, layout tag holds information about which model(s) is/are using in layout.

<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <data>
        <variable name="user" type="chintan.rathod.databindingdemo.Model.User"/>
    </data>
    ...
</laoyout>

Step 5

To use item in RecyclerView, we require to create a ViewHolder. Create a new class and name it UserViewHolder. Open newly created class and paste below code.

public class UserViewHolder extends RecyclerView.ViewHolder {
    private UserItemBinding binding;
 
    public UserViewHolder(View itemView) {
        super(itemView);
        binding = DataBindingUtil.bind(itemView);
    }
 
    public void bind(User user) {
        binding.setUser(user);
    }
}

Here, UserItemBinding class is autogenerated by project. When you use data tag in your layout, Android will auto generate a class with layout filename and a suffix “Binding”. In out case, layout file name is user_item.xml so autogenerated class is userItemBinding. This class holds all binding i.e. user in our case.

Step 6

Create a class UserAdapter. This class is used for bindig your view and data provided. Paste below code.

public class UserAdapter extends RecyclerView.Adapter<UserViewHolder> {
    private final List<User> users;

    public UserAdapter(List<User> users) {
        this.users = users;
    }
 
    @Override
    public UserViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        Context context = parent.getContext();
        LayoutInflater inflater = LayoutInflater.from(context);
        View statusContainer = inflater.inflate(R.layout.user_item, parent, false);
        return new UserViewHolder(statusContainer);
    }
 
    @Override
    public void onBindViewHolder(UserViewHolder holder, int position) {
        User status = users.get(position);
        holder.bind(status);
    }
 
    @Override
    public int getItemCount() {
        return users.size();
    }
}

Here, when you use

holder.bind(status);

code, this will actually bind your user object to your layout. There is nothing complex in this adapter class.

Step 7

Open your activity class. We require to add some lines of code to apply adapter to RecyclerView

public class DataBindingListActivity extends AppCompatActivity {

    private RecyclerView list;
    
    private UserAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.binding_list_activity);

        list = (RecyclerView) findViewById(R.id.list);
        list.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));

        User user1 = new User("Chintan Rathod",28);
        User user2 = new User("Saroj Rathod",27);
        User user3 = new User("Maulik Rathod",25);

        ArrayList<User> userList = new ArrayList<>();
        userList.add(user1);
        userList.add(user2);
        userList.add(user3);

        adapter = new UserAdapter(userList);
        list.setAdapter(adapter);
    }
}

You can see that I created a list of User and provide them to an adapter. This adapter is applied to RecyclerView.

Now it’s time to execute our code.

Output

Summary

In this article, we learnt how data binding can be used with RecyclerView.

Download

Source code for this article is available here.

Protected by Copyscape

Share on Facebook9Share on Google+8Tweet about this on TwitterShare on LinkedIn0Share on Reddit0Pin on Pinterest0Share on Tumblr0Email this to someone