Basic text field binding

suggest change

Gradle (Module:app) Configuration

android {
    ....
    dataBinding {
        enabled = true
    }
}

Data model

public class Item {
    public String name;
    public String description;

    public Item(String name, String description) {
        this.name = name;
        this.description = description;
    }
}

Layout XML

The first step is wrapping your layout in a <layout> tag, adding a <data> element, and adding a <variable> element for your data model.

Then you can bind XML attributes to fields in the data model using @{model.fieldname}, where model is the variable’s name and fieldname is the field you want to access.

item_detail_activity.xml:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
   <data>
       <variable name="item" type="com.example.Item"/>
   </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="@{item.name}"/>

       <TextView
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="@{item.description}"/>

   </LinearLayout>
</layout>

For each XML layout file properly configured with bindings, the Android Gradle plugin generates a corresponding class : bindings. Because we have a layout named item_detail_activity, the corresponding generated binding class is called ItemDetailActivityBinding.

This binding can then be used in an Activity like so:

public class ItemDetailActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       ItemDetailActivityBinding binding = DataBindingUtil.setContentView(this, R.layout.item_detail_activity);
       Item item = new Item("Example item", "This is an example item.");
       binding.setItem(item);
    }
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents