savedInstanceState) { super.onCreate(savedInstanceState); binding = DataBindingUtil.setContentView(this, R.layout.main_activity); } private void updateUser(User user) { binding.setUser(user); } Call this to bind layout to Activity instead of calling setContentView() Bind user data to views
public ObservableField<String> firstName; public void setFirstName(String firstName) { this.firstName = new ObservableField<>(firstName); } An Observable field
Responsible for binding data to views • May contain business logic code public class User extends BaseObservable { private String firstName; @Bindable public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; notifyPropertyChanged(BR.firstName); } }
= new ObservableField<String>(); public final ObservableInt age = new ObservableInt(); } user.name.set("Name"); user.age.set(20); An object wrapper to make it observable. Observable field classes may be used instead of creating an Observable object:
… } <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="@{user::contactAction}"/> Declare a method with a parameter Bind method to event using “::” The parameters of the method must match the parameters of the event listener.
contactAction(View view, User user) { … } <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="@{ (e) -> user.contactAction(e , user) }"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="@{ () -> user.contactAction(user) }"/> 1 2 Only your return value must match the expected return value of the listener
Different parameters The expression is evaluated when the event occurs. Method references Fixed number of parameters The expression is evaluated at binding time Listener Objects Existing apps