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

(gtxtreme123) #1

Chapter 20  Data Binding and MVVM


Observable data


All may appear to be well, but darkness lies hidden in your code. You can see it if you scroll down
(Figure 20.12).


Figure 20.12  Déjà vu


See the item “67_INDIOS2” at the bottom? It was at the top, too. Scroll up and down repeatedly, and
you will see other file titles repeatedly appearing in unexpected, seemingly random places.


This is happening because your layout has no way of knowing that you updated SoundViewModel’s
Sound inside SoundHolder.bind(Sound). Your view model does not talk back to the layout file, as
depicted in Figure 20.10.


Your next job will be to add this connection. To do this, your view model needs to implement data
binding’s Observable interface. This interface lets your binding class set listeners on your view model
so that it can automatically receive callbacks when its fields are modified.


Implementing the whole interface is possible, but it is also a lot of work. We do not shy away from
hard work here at Big Nerd Ranch, but we prefer to avoid it when we can. So we will instead show you
how to do it the smart way, with data binding’s BaseObservable class.

Free download pdf