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


Binding to a ViewModel


Now to integrate the view model into your layout file. The first step is to declare a property on your
layout file, like so:


Listing 20.22  Declaring the view model property (list_item_sound.xml)


<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">



name="viewModel"
type="com.bignerdranch.android.beatbox.SoundViewModel"/>

This defines a property named viewModel on your binding class, including a getter and setter. Within
your binding class, you can use viewModel in binding expressions.


Listing 20.23  Binding your button title (list_item_sound.xml)


<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">



name="viewModel"
type="com.bignerdranch.android.beatbox.SoundViewModel"/>

android:layout_width="match_parent"
android:layout_height="120dp"
android:text="@{viewModel.title}"
tools:text="Sound name"/>

Within the binding mustache, you can write simple Java expressions, including chained method calls,
math, and anything else you want to include. You also get some “syntactic sugar” – conveniences to
save you typing. For example, viewModel.title above is shorthand for viewModel.getTitle(). Data
binding knows how to translate your property reference into the appropriate method call.


The last step is to hook up your view model. Create a SoundViewModel and attach it to your binding
class. Then add a binding method to your SoundHolder.


Listing 20.24  Hooking up the view model (BeatBoxFragment.java)


private class SoundHolder extends RecyclerView.ViewHolder {
private ListItemSoundBinding mBinding;


private SoundHolder(ListItemSoundBinding binding) {
super(binding.getRoot());
mBinding = binding;
mBinding.setViewModel(new SoundViewModel(mBeatBox));
}


public void bind(Sound sound) {
mBinding.getViewModel().setSound(sound);
mBinding.executePendingBindings();
}
}

Free download pdf