Develop your application with Data Binding — Binding View and Data — Part 1

Harin Trivedi
AndroidPub
Published in
5 min readMay 2, 2017

There is always need for a faster & smarter development in tight deadline projects. Even you might get bored while writing so many boilerplate lines of code for managing the views in your screen. Yes, I am talking about finding your views, setting values, assigning actions and many other things to implement your business logic on screen.

It becomes clumsy, especially in case when you are working with a screen having lots of input fields, managing them with validation, handling visibility and other attributes of the components.

ref:https://giphy.com

There is always been need of a little automation in the development process where you can save your time and focus more on the logic rather than writing code for presentation only. There are some helpful libraries available to solve this problem like Butter Knife. It is a useful library based on annotations for defining views and actions.

But today, I want to talk about Data Binding support library which has been provided (for long time unknowingly) to solve this matter in more advanced way. And of course, if you are using Android Studio as a development tool, it’s super easy to go with it. Hmmm, so much discussion :) let’s jump right in into it step by step…

Step 1:

It’s a support library, so you can use it with all Android platform versions back to Android 2.1 (API level 7+). To enable it, simple add below in your build.gradle file of main module.

android {
....
dataBinding {
enabled = true
}
}

Step 2:

Oh! very easy. Now you can use super cool data binding feature in your project. Cool!. Now let’s see how to use it. Let’s modify your layout file and add <layout> tag as a root element.

<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
</data>

<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
andriod:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello"/>
</LinearLayout>
</layout>

You might ask what is <data></data>! This tag is mandatory to enable your layout file to be used for data binding. But we’ll see its purpose later.

Step 3:

Now when using data binding, you need to modify your code for inflating the layout.

MainActivityBinding binding = DataBindingUtil.setContentView(this, R.layout.main_activity);

Let’s understand above line of code. Here DataBindingUtil is the class which generated a binding class behind the scene which will capture and store all view references within it. As per the rule, the class name will be decided from layout file name, replacing starting character of word with capital and removing the underscore symbol. So main_activity will be converted to MainActivityBinding!

Now, how to access the TextView? As per the name of id given to any component, binding class will generate a variable to access it. For our example,

String text = binding.textView.getText().toString();
binding.textView.setText("Binding Demo");

That’s super easy, Isn’t it? You can access any component in your layout similar way you were accessing after finding all views manually and using it.

Step 4:

Now let’s see use of the <data> tag. Here you can bind a data model directly with the layout! Oh! Is it possible? Let’s make a user model class first.

public class User {
private final String firstName;
private final String lastName;
public User(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return this.firstName;
}
public String getLastName() {
return this.lastName;
}
}
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable name="user" type="com.example.User"/>
</data>

<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
andriod:id="@+id/tvFirstName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{user.firstName}"/>
<TextView
andriod:id="@+id/tvLastName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{user.lastName}"/>
</LinearLayout>
</layout>

In activity you need to pass instance of user model to make this work.

User user = new User("First", "User");
binding.setUser(user);
  1. variable property allows you to define what data you want to pass. In name you can write user defined instance name and in type you need to give class path.
  2. @ { … } allows you to specify value by accessing the instance properties, in our example user.firstName, which actually refers getFirstName() method of the model class. You need to specify getter methods for attributes you want to refer inside the layout file through data binding.
  3. When you defined name in <variable> tag, it generates a setter method to pass the instance of the model class. So, binding.setUser() will allow you to pass the instance to layout.

Now if you run the application, it will show first name and last name displayed in text views without finding views or setting values to each of them, pretty cool right?

ref:https://giphy.com

“Question 1: What are the different ways to use binding?”

We already did it for activity in our example. When using fragment or adapter, we generally use ViewInflater to inflate layout. Now to use it with data binding,

MyLayoutBinding binding = DataBindingUtil.inflate(layoutInflater, R.layout.my_layout, viewGroup, false);

Here it will return MyLayoutBinding class which will allow you to refer any component inside layout as well as pass data to it.

“Question 2: What kind of data can be passed to layout?”

<data>
<import type="com.example.User"/>
<import type="java.util.List"/>
<import type="android.graphics.drawable.Drawable"/>
...
<variable name="user" type="User"/>
<variable name="image" type="Drawable"/>
<variable name="note" type="String"/>
<variable name="userList" type="List&lt;User&gt;"/></data>
  1. You can pass an instance of custom class (user)
  2. You can pass a drawable resource reference (image)
  3. You can pass any primitive type value like int, string, double etc. (note)
  4. You can even pass instance of collections like List, Map etc. (userList)
  • But as you can see you need to format text to use inside xml file as List<User> need to be written as List&lt;User&gt;
  • Another thing thing to remember is, when you are mentioning class name directly in type attribute, you have to add import statement for them. You can see imports for User, List and Drawable class.

“Question 3: What if I have included a layout inside layout?”

That’s a good question! Yes, here also you can use data binding. In your child layout you have to modify it same way we did it in step 2. Than in your include tag you can bind your data with ‘bind’ attribute like given below: (It will generate binding class InnerLayoutBinding as file name is inner_layout.xml.)

<include layout="@layout/inner_layout"
bind:user="@{user}"/>

So we learned view referencing and binding the data to layout through data binding. This will drastically decrease unnecessary efforts for finding views and setting values to each of them. This is also helpful to separate your presentation and business logic.

--

--

Harin Trivedi
AndroidPub

Software Engineer, Exploring the world of Technology!