Android data binding - Tuong-Nguyen/PreparationEduLog GitHub Wiki
Enable databinding in app.gradle
file
android {
...
dataBinding {
enabled = true
}
}
- A binding class is generated base on the layout
- Ex:
login_activity.xml
layout ->LoginActivityBinding
class
- Ex:
- Define a view model class
public class User {
private String username;
private String password;
public User(){
this.username = "Test User";
this.password = "123456";
}
public String getUsername() {
return username;
}
public void setUsername(String username) { this.username = username; }
public String getPassword() {
return password;
}
public void setPassword(String password) { this.password = password; }
}
- Add variable to the layout for binding
<data>
<variable name="user" type="com.example.lnthao.mvpdemo.presentation.viewmodel.User" />
</data>
- Binding to EditText
<EditText android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{user.username}"/>
- Set binding class in view (activity)
binding = DataBindingUtil.setContentView(this, R.layout.login_activity);
- Set view model
User user = new User();
binding.setUser(user);
- Extends view model class with
BaseObservable
- Use @Bindable for getter
- Watch the change of setter by
notifyPropertyChanged(BR.username)
method - In layout, use @={ to binding instead of @{