What's the need to call DataBindingUtil.setContentView() when using Data Binding Library?

你。 提交于 2021-01-28 05:52:37

问题


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:

  1. made a temp_layout.xml which contains 2 text views with ids 'tv1' and 'tv2'

  2. added the <layout> tag as root

  3. 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?


回答1:


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.




回答2:


DataBindingUtil.setContentView() set the Activity's content view to the given layout and return the associated binding. It is same as Activity's setContentView().

If you not call DataBindingUtil.setContentView() or setContentView(), you will only get a blank screen.



来源:https://stackoverflow.com/questions/45706965/whats-the-need-to-call-databindingutil-setcontentview-when-using-data-binding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!