Start a Project

Data Binding in android with View ID

I was working on Data binding in my android application for quite some time and thought that there is only one method to bind data is via Objects or variables i.e. for every single value to bind with the layout I either have to save it to a variable or make an object. Also for some functionality and feature we still need View ID defined in layout in our Activity/Fragment. So thought of it as a limitation of data binding but I was wrong.

Android Developers at Google must have thought of it initially and yes you can access the View ID defined in your XML in your Activity/fragment without using findViewById(). And its very simple as well, you don’t have to do anything your Binding class has already did it for you.

All the View ID (s) you have declared in your XML are by default converted in a Variable in your Binding class, its name is the CamelCase version of the ID you defined like for android:id=”@+id/item_view” the generated variable will be itemView. Now you can access the variable through binding variable and can apply and method on it or whatever is your requirement.

For example if I have a layout info_layout like

Then in your activity you can either inflate the layout wherever you want like

Or you can set it with replacing setContentView() of your Activity as

If you have two view in your XML that become same after applying CamelCase on them then also you don’t need to worry. Because DataBinding can deal with it too. it will give one View as CamelCase name and other one with added numeric one after that i.e. MainView and MainView1. So what do you think about data binding now. Isn’t it cool?

<<previous

Exit mobile version