DataBinding: how can I make sure that as a result of a modification of the data model the view is updated accordingly? Eg:
public class MyActivity extends AppCompatActivity {
private MyActivityBinding mBinding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBinding = DataBindingUtil.setContentView(this, R.layout.my_activity);
mBinding.setMyModel(new MyModel());
}
public void onClickAnItem(View view) {
MyModel model = mBinding.getMyModel();
model.setField1 = "Jhon";
model.setField2 = "Dho";
mBinding.executePendingBindings();
}
}
In this case the model "MyModel" has been modified but view is not updated; what did I miss?
Reading documentation I found a solution, first of all: Any plain old Java object (POJO) may be used for data binding, but modifying a POJO will not cause the UI to update! To give MyModel data object the ability to notify when data changes I made this modifications:
private class MyModel extends BaseObservable {
private String field1;
private String field2;
@Bindable
public String getField1() {
return this.field1;
}
@Bindable
public String getField2() {
return this.field2;
}
public void setField1(String firstName) {
this.field1 = firstName;
notifyPropertyChanged(BR.field1);
}
public void setField2(String lastName) {
this.field2 = lastName;
notifyPropertyChanged(BR.field2);
}
}
I hope this can help someone else Documentation here