Its all hyped up now. Data Binding is gradually seeing itself in many android projects and is quite matured now to be used in a production android application

What you’ll learn?

Replace Butterknife with Data Binding

Let’s get started

This repository has the code that will be used in the post

I have created a new android project using the blank activity template and added butterknife library to build.gradle. I have a simple layout with two TextViews

In the MainActivity.java file we typically create binding using @Bind Annotation

Now lets replace it using Data Binding

To get started with Data Binding, download the library from the Support repository in the Android SDK manager.To configure your app to use data binding, add the dataBinding element to your build.gradle file in the app module.

First, add the following into the app level build.gradle file to enable Data Binding

android {

....

dataBinding {

enabled = true

}

}

Don’t forget to Sync the project

Data-binding layout files are slightly different and start with a root tag of layout followed by a data element and a view root element. In our case we wont be using the data element and will only be dealing with view.

Inflating the layout is slightly different than we used. By default, a Binding class will be generated based on the name of the layout file, converting it to Pascal case and suffixing “Binding” to it. In our case we had a layout called activity_main.xml so the Binding class will be called `ActivityMainBinding`

We inflate the layout by using the DataBindingUtil class and setting the binding to a variable binding of type ActivityMainBinding

ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);

This class holds all the bindings from the layout properties to the layout's Views and knows how to assign values for the binding expressions.The easiest means for creating the bindings is to do it while inflating. So our MainActivity.java class would look like this.