Introduction to Android DataBinding






If you are already a Mobile Application Developer or just started to learn Android App Development, then you must be tired of writing (findViewById(R.id.xxx)) every time...right?

Initially, it felt so good in writing each line of code by yourself but later as you progress all these repetitive lines will start to annoy you.


So, Android has a library that will minimize all this effort and allow you to focus on the main work rather than writing the boilerplate code.

Let me introduce you to the DataBinding

The Data Binding Library is a support library that allows you to bind UI components in your layouts to data sources in your app using a declarative format rather than programmatically.

Let's Simplify more,

DataBinding is a library that creates the objects of all the components you use in your XML and allows you to use them directly without initializing them in your JAVA Class.


 Still didn't understand.??? don't worry..

It refrains you from initializing each component using findViewById(). It takes care of all the initialization part and let you focus on writing quality code.

Enough explaining, let's implement it in our project.


Enable DataBinding:

Open the build.gradle located under app and enable dataBinding under android module.Add


dataBinding{
    enabled = true}

Sync your project and you are good to go.

Let's create our layout activity_main.xml. 

Here if you see our root that is <layout> </layout>.Adding <layout> tag means we are implementing DataBinding in this activity.

Note: Inside the <layout> tag remove the android:height and android:width attributes, otherwise it will give you error in runtime.

 Now we have successfully added databinding in our activity.

We are done here, Let's go to our Class File MainActivity.java.
 

With DataBinding, a Binding class is auto generated from your layout file. The class is named using your layout file name by default name is generated by capitalizing the first letter of each word after an underscore, removing all underscores, and adding 'Binding' to the name. As such, acitivity_main.xml will result in a class called ActivityMainBinding. 



To associate our activity_main.xml layout, where we have implemented databinding, we have to invoke DataBindingUtil.setContentView().


And you are done..!!!.



Today, we have learned what is DataBinding in android? and How to implement it in android?



This is very basic of DataBinding. It is capable of doing much more than this and we will discuss the advanced concept in future. Till then Keep Learning, Keep coding... 😄😄!!
 











Comments