I am learning to use Data Binding Library. I came to know that it removes the need to call findViewById() manually and makes the code more robust and readable.
To understand the use, I did the following:
made a temp_layout.xml which contains 2 text views with ids 'tv1' and 'tv2'
added the <layout>
tag as root
clicked on 'build project'
Now I found that a new 'TempLayoutBinding' class was available which contained the variables 'tv1' and 'tv2'.
My question is that, even when I already specified the <layout>
tag in the temp_layout.xml, why do I still need to call mBinding = DataBindingUtil.setContentView(...)
?
What specifically does it do?
SetContentView is used to fill the window with the UI provided from layout file incase of setContentView(R. layout. somae_file). Here layoutfile is inflated to view and added to the Activity context(Window).
DataBindingUtil.setContentView(this, R.layout.activity_main) DataBindingUtil is a Utility class to create ViewDataBinding from layouts. A binding class is generated for each layout file. The default naming convention used for the generated class is based on the name of the layout file.
Android Studio Supports Data BindingSyntax Highlighting. XML code completion. Flagging of expression language syntax errors. Navigate to declaration.
What the regular setContentView(layoutRes)
does is display your UI in the current activity and inflates it into a view that's added to the Activity Context, so you can call findViewById and other methods over the inflated layout.
In data binding, the regular setContentView(layoutRes)
is replaced with DataBindingUtil.setContentView(context, layoutRes)
, it does all the above plus creating the binding object, it does findViewById and all other data binding related tasks under the hood and gives you the binding object that's ready for use.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With