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

(gtxtreme123) #1
Binding to a ViewModel

Inside your constructor, you construct and attach your view model. Then, in your bind method, you
update the data that view model is working with.


Calling executePendingBindings() is not normally necessary. Here, though, you are updating binding
data inside a RecyclerView, which updates views at a very high speed. By calling this method, you
force the layout to immediately update itself, rather than waiting a millisecond or two. This keeps your
RecyclerView looking spiffy.


Finally, finish hooking up your view model by implementing onBindViewHolder(...).


Listing 20.25  Calling bind(Sound) method (BeatBoxFragment.java)


return new SoundHolder(binding);
}


@Override
public void onBindViewHolder(SoundHolder holder, int position) {
Sound sound = mSounds.get(position);
holder.bind(sound);
}


@Override
public int getItemCount() {
return mSounds.size();
}


Run your app and you will see titles on all the buttons on your screen (Figure 20.11).


Figure 20.11  Button titles filled in

Free download pdf