Android setVariable(BR.xyz, model) 和 databinding.setXYZ(model) 有什么区别

标签 android android-layout android-databinding

我正在研究 android 数据绑定(bind),遇到了我们可以使用以下两种方式设置模型的场景:

 User user = new User("User", "Abc"); // this is a model
dataBinding.setVariable(BR.user, user);
dataBinding.executePendingBindings(); // and we have to do this... Why?

我们也可以这样设置:

binding.setUser(user);

谁能解释一下这两者之间的区别是什么?

用户模型:

public class User{
public String fName;
public String lName;

public User(String fName, String lName){
this.fName = fName;
this.lName = lName;
   }
}

最佳答案

考虑一下当您有一个不共享公共(public)绑定(bind)布局的抽象类时的情况(当然除了父类(super class) ViewDataBinding,所有绑定(bind)布局都继承自该父类(super class)):

public abstract classs EditorActivityFragment<T extends ViewDataBinding> {

在这个类的 onCreateView() 中,您将无法使用任何生成的方法将您的变量设置为绑定(bind),因为除了 ViewDataBinding 之外没有通用的父类(super class),因此您将被迫使用反射,或者你可以使用方便的方法setVariable():

binding.setVariable(BR.viewModel,myViewModel);

我希望这有助于更好地解释此方法的用例。

关于Android setVariable(BR.xyz, model) 和 databinding.setXYZ(model) 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35309369/

相关文章:

android - 如何通过数据绑定(bind)传递NumberPicker值(onValueChange)?

android - 无法创建 "Single-action control"通知 android wear

具有多个布局的 Android ListView : why bother with `getItemViewType` at all?

android - 如何使用移动模块中的类?

android - ConstraintLayout 剪辑文本中的 TextView

android - 如何在 Android 中获取图像大小的坐标?

android - 如何在数据绑定(bind)表达式中进行强制转换?

java - 自定义控件中的android数据绑定(bind)

android - Facebook 状态更新

android - 当 AccountManager 删除帐户时,SyncAdapter 会收到通知吗?