Android What is the difference between setVariable (BR.xyz, model) and databinding.setXYZ (model)

I was working on data binding to androids and came across a script that we can install for the model using the following two methods:

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

and we can also install:

 binding.setUser(user); 

Can anyone explain this what is the difference between the two?

User Model:

 public class User{ public String fName; public String lName; public User(String fName, String lName){ this.fName = fName; this.lName = lName; } } 
+5
source share
2 answers

They do the same thing. According to docs , sometimes the type of a variable cannot be determined, so you have to use the setVariable() method. Under normal conditions, the setX() method will be created. You are better off using the generated methods.

+6
source

Consider the case when you have an abstract class that does not have a common binding template (except, of course, the ViewDataBinding superclass, which inherits all binding layouts):

 public abstract classs EditorActivityFragment<T extends ViewDataBinding> { 

In this' onCreateView() class, you cannot use any generated methods to bind a variable to a binding, since there is no common superclass except ViewDataBinding, so you will be forced to use reflection or you can use the convenience method setVariable() :

 binding.setVariable(BR.viewModel,myViewModel); 

Hope this helps to better explain the use case for this method.

+3
source

Source: https://habr.com/ru/post/1242688/


All Articles