publicvoidonBindViewHolder(BindingHolder holder, int position){ final T item = mItems.get(position); holder.getBinding().setVariable(BR.item, item); holder.getBinding().executePendingBindings(); }
classViewModelActivityextendsAppCompatActivity{ @Override protectedvoidonCreate(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); } }
classViewModelActivityextendsAppCompatActivity{ @Override protectedvoidonCreate(Bundle savedInstanceState){ // Obtain the ViewModel component. UserModel userModel = ViewModelProviders.of(getActivity()) .get(UserModel.class); // Inflate view and obtain an instance of the binding class. UserBinding binding = DataBindingUtil.setContentView(this, R.layout.user); // Assign the component to a property in the binding class. binding.viewmodel = userModel; } }
/** * A ViewModel that is also an Observable, * to be used with the Data Binding Library. */ classObservableViewModelextendsViewModelimplementsObservable{ private PropertyChangeRegistry callbacks = new PropertyChangeRegistry(); @Override protectedvoidaddOnPropertyChangedCallback( Observable.OnPropertyChangedCallback callback){ callbacks.add(callback); } @Override protectedvoidremoveOnPropertyChangedCallback( Observable.OnPropertyChangedCallback callback){ callbacks.remove(callback); } /** * Notifies observers that all properties of this instance have changed. */ voidnotifyChange(){ callbacks.notifyCallbacks(this, 0, null); } /** * Notifies observers that a specific property has changed. The getter for the * property that changes should be marked with the @Bindable annotation to * generate a field in the BR class to be used as the fieldId parameter. * * @param fieldId The generated BR id for the Bindable field. */ voidnotifyPropertyChanged(int fieldId){ callbacks.notifyCallbacks(this, fieldId, null); } }