普通对象可以用在data binding布局文件中,但是对象的修改不会引起UI的自动更新,所以建议使用observable对象,observable类包含objects, fields, 和 collections.
Observable fields包括:
ObservableBoolean
ObservableByte
ObservableChar
ObservableShort
ObservableInt
ObservableLong
ObservableFloat
ObservableDouble
ObservableParcelable
Observable collections包含:ObservableArrayList和ObservableArrayMap
Observable objects指实现了Observable接口的类,但是我们通常通过集成BaseObservable来实现Observable objects,因为BaseObservable已经实现了通知和监听注册的方法。
private static class User extends BaseObservable {
private String firstName;
private String lastName;
@Bindable
public String getFirstName() {
return this.firstName;
}
@Bindable
public String getLastName() {
return this.lastName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
notifyPropertyChanged(BR.firstName);
}
public void setLastName(String lastName) {
this.lastName = lastName;
notifyPropertyChanged(BR.lastName);
}
}
Bindable注解会在BR类中生产一个域来定义当前的变量。比如我们可以使用BR.firstName来标志变量firstName。
我们可以使用LiveData来自动的更新UI,
class ViewModelActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// Inflate view and obtain an instance of the binding class.
UserBinding binding = DataBindingUtil.setContentView(this, R.layout.user);
// Specify the current activity as the lifecycle owner.
binding.setLifecycleOwner(this);
}
}
需要调用setLifecycleOwner
网友评论