Why you should use Android Data Binding

Why I started used data binding

After my first blog post about Fastest way for creating RecyclerView Adapter, a couple of you post a comment why I don’t use Data Binding instead of Butterknife. To be honest, I didn’t try to use it simply because I’m used to using Butterknife. I know now that I was terribly wrong, so for every developer like me, here is post to try to convince you to start using data binding.

How to start

First of all, you will need to use Gradle 1.5.0 or above. Now open your app-level gradle and add this line under android:

Sync gradle and you are ready to go. I think that best way to learn new this is by going with a real example, so I will build this mini two screen Android app just to show you advantages of android data binding.

Best way to learn

My opinion is that in order to learn new thing, you need to practice on a real example, something like: it’s better to develop one app then read 10 tutorials. For this example, I will create one extremely simple app. The first screen will be RecyclerView when you click on the list item, it will open DetailsActivity with more info. I know that this is a stupid app, but still, it’s way bette then 8 Chinese octopus recipes. 

So let’s see our item_user.xml file

We need to wrap our LinearLayout (or any, other root view) with layout tag, and under that optionally we can add some data. In a this case, we imported User and UserHandler class.


So let’s compare our example with the more traditional way of doing things. We will change our ViewHolder from this:

into something like this:

So no more findViewById, awesome right? We will need change one more thing and that is onBindViewHolder method.

Everything that we use as a variable in our xml, we need to add into our binding with setVariable method. Don’t forget to call executePendingBindings method at the end.

Now we need set texts and everything else directly in our xml file.

So this will get company string from our User class and bind it to TextView. If we need more complex code, for example String formating we can use it again directly in our xml.

or we need handle click event with passing our user data

You can even have if login right into layout


At first, I din’t like idea haveing login inside layout file, but result is much cleaner Java code, without all that findViewById boilerplate code. I encourage you to try it if you are not already, and you can start with my example on Github. There you can also find no-data-bindig branch so you can compare code side by side.