Android Programming The Big Nerd Ranch Guide by Bill Phillips, Chris Stewart, Kristin Marsicano (z-lib.org)

(gtxtreme123) #1
Observable data

Three steps are required with this method:



  1. Subclass BaseObservable in your view model.

  2. Annotate your view model’s bindable properties with @Bindable.

  3. Call notifyChange() or notifyPropertyChanged(int) each time a bindable property’s value
    changes.


In SoundViewModel, this is only a few lines of code. Update SoundViewModel to be observable.


Listing 20.26  Making view model observable (SoundViewModel.java)


public class SoundViewModel extends BaseObservable {
private Sound mSound;
private BeatBox mBeatBox;


public SoundViewModel(BeatBox beatBox) {
mBeatBox = beatBox;
}


@Bindable
public String getTitle() {
return mSound.getName();
}


public Sound getSound() {
return mSound;
}


public void setSound(Sound sound) {
mSound = sound;
notifyChange();
}
}


When you call notifyChange() here, it notifies your binding class that all of the Bindable fields on
your objects have been updated. The binding class then runs the code inside the binding mustaches
again to repopulate the view. So now, when setSound(Sound) is called, ListItemSoundBinding will
be notified and call Button.setText(String) as you specified in list_item_sound.xml.


Above, we mentioned another method: notifyPropertyChanged(int). The
notifyPropertyChanged(int) method does the same thing as notifyChange(), except it is more
particular. By writing notifyChange(), you say, “All of my bindable properties have changed; please
update everything.” By writing notifyPropertyChanged(BR.title), you can instead say, “Only
getTitle()’s value has changed.”


Run BeatBox one more time. This time, you should see the right thing when you scroll around
(Figure 20.13).

Free download pdf