Table of Contents

About

Data Binding want you to minimize the glue code necessary to bind your application logic and layouts.

By default, a Binding class will be generated based on the name of the layout file, converting it to Pascal case and suffixing “Binding” to it.

Example: The layout file main_activity.xml generate a class named MainActivityBinding.

This class holds all the bindings from the layout properties (e.g. the user variable) to the layout's Views and knows how to assign values for the binding expressions.The easiest means for creating the bindings is to do it while inflating.

Example

The layout

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
   <!-- Zero or more import elements may be used inside the data element.  -->
   <data>
       <variable name="user" type="com.example.User"/>
   </data>
   <LinearLayout
       android:orientation="vertical"
       android:layout_width="match_parent"
       android:layout_height="match_parent">
       <TextView android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="@{user.firstName}"/>
       <TextView android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="@{user.lastName}"/>
   </LinearLayout>
</layout>

The Activity Class

@Override
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   MainActivityBinding binding = DataBindingUtil.setContentView(this, R.layout.main_activity);
   User user = new User("Test", "User");
   binding.setUser(user);
}

where:

  • ActivityMainBinding is just the class representation of the layout XML R.layout.activity_main
  • DataBindingUtil is an utility class to create ViewDataBinding from layouts.

Documentation / Reference