Android data binding — 1

Binding static value

This story is about Android data binding, but from the point of view of beginner. This story also uses MVVM approach in examples.

First sample

Very first, take a look at original Android profile, and see how to use Binding in most simplest way.

Step 1: Enable Binding module (make sure using latest version of Android & Android studio

To use data binding, Android Plugin for Gradle 1.5.0-alpha1 or higher is required.
Add dataBinding block in app build.gradle

Step 2. Write a simple ViewModel class

Step 3. Add ViewModel to layout

activity_main.xml before and after binding

①: Add layout tag covers original layout
②: Define data. See google document for more detail. Following MVVM model, we define “viewModel” variable here (or any other name you like)
③: Mapping TextView text attribute to viewModel property (see SampleViewModel class above)

Step 4: Bind view-model data to view

MainActivity.java before and after binding

ActivityMainBinding is auto-generated, based on layout file name (here is activity_main.xml) by converting it to Pascal case and suffixing “Binding” to it

Finally, run project and see result



TOC

Part 1: Binding static value

Part 2: Binding user event

Part 3: EditText & Two-way data binding

Part 4: Sample form data binding