Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I was working on android data-binding and came across the scenario that we can set a model using following two ways:

 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 set like:

binding.setUser(user);

Can anyone explain this what the difference between these two?

User Model:

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

public User(String fName, String lName){
this.fName = fName;
this.lName = lName;
   }
}
like image 765
asad.qazi Avatar asked Feb 10 '16 07:02

asad.qazi


2 Answers

Consider the case when you have a abstract class which does not share a common binding layout (except for of course the superclass ViewDataBinding which all binding layouts inherit from):

public abstract classs EditorActivityFragment<T extends ViewDataBinding> {

In this class' onCreateView() you won't be able to use any generated methods to set your variable to the binding, as there's no common superclass besides the ViewDataBinding, thus you will be forced to use reflection, or you can use the convenience method setVariable():

binding.setVariable(BR.viewModel,myViewModel);

I hope that helps explain the use case for this method better.

like image 65
AutoM8R Avatar answered Sep 23 '22 13:09

AutoM8R


They do the same thing. According to the docs, sometimes the type of the variable can't be determined, so you will have to use the setVariable() method. Under normal circumstances, the setX() method(s) will be generated. You are better off using the generated methods.

like image 33
Jarett Millard Avatar answered Sep 22 '22 13:09

Jarett Millard