使用数据绑定库时,需要调用DataBindingUtil.setContentView()吗? [英] What's the need to call DataBindingUtil.setContentView() when using Data Binding Library?

查看:294
本文介绍了使用数据绑定库时,需要调用DataBindingUtil.setContentView()吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习使用数据绑定库.我知道它消除了手动调用findViewById()的需要,并使代码更加健壮和可读.

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. 制作了一个temp_layout.xml,其中包含2个ID为'tv1'和'tv2'的文本视图

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

< layout> 标记添加为根

点击构建项目"

现在我发现可以使用一个新的'TempLayoutBinding'类,其中包含变量'tv1'和'tv2'.

Now I found that a new 'TempLayoutBinding' class was available which contained the variables 'tv1' and 'tv2'.

我的问题是,即使我已经在temp_layout.xml中指定了< layout> 标记,为什么我仍然需要调用 mBinding= DataBindingUtil.setContentView(...)?具体是做什么的?

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(layoutRes)的作用是在当前活动中显示您的UI,并将其膨胀为已添加到视图中的视图.活动上下文,因此您可以在展开后的布局上调用findViewById和其他方法.

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.

在数据绑定中,常规的 setContentView(layoutRes)被替换为 DataBindingUtil.setContentView(context,layoutRes),它完成了上述所有操作并创建了绑定对象,它确实找到了findViewById和所有其他与数据绑定有关的任务,并为您提供了可供使用的绑定对象.

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.

这篇关于使用数据绑定库时,需要调用DataBindingUtil.setContentView()吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆