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


Simple data binding


The next job is to inflate fragment_beat_box.xml and hook up its RecyclerView. This is a job that
you have done before. But this time, you will use data binding to speed up your work.


Start by enabling data binding in your app’s build.gradle file.


Listing 20.4  Enabling data binding (app/build.gradle)


versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
}
}
dataBinding {
enabled = true
}
}


dependencies {


This turns on the IDE integration that will allow you to access the classes data binding will generate for
you and integrate that class generation into your build.


To use data binding within a particular layout file, you have to change it into a data binding layout file.
The way you do that is by wrapping the entire XML file in a tag.


Listing 20.5  Wrapping it up (res/layout/fragment_beat_box.xml)


<layout
xmlns:android="http://schemas.android.com/apk/res/android">
<android.support.v7.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>



The tag is your signal to the data binding tool that it should get to work on your layout file.
Once it is done, it will generate a binding class for you. By default, this class is named after your
layout file, but instead of using snake_case, it is switched to CamelCase naming style.


Your fragment_beat_box.xml file has already generated a binding class, called
FragmentBeatBoxBinding. This class is what you will use for data binding: Instead of inflating a
view hierarchy with a LayoutInflater, you will inflate an instance of FragmentBeatBoxBinding.
FragmentBeatBoxBinding will hold on to the view hierarchy for you in a getter called getRoot(). In
addition to that, it holds on to named references for each view you tagged with an android:id in your
layout file.

Free download pdf