Android - Data Binding (ViewDataBinding)

Card Puncher Data Processing

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





Discover More
Card Puncher Data Processing
Android - Inflate (a layout XML to a view UI object)

In Android, you can create an UI: decoratively through a layout XML with Java object view (viewgroup for container and views for widget) In this context, Inflate means reading a layout XML (often...
Android Xml Layout Attribute Reference
Android - Layout File (XML)

A layout XML is a declarative way of creating an UI. To define the GUI in android, you can do it: at runtime in the code with the ViewGroup object (UI container) and View obejct (widgets) at load...



Share this page:
Follow us:
Task Runner