Essential Android Data Binding Library edit forum

Basic text field binding

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 tag, adding a element, and adding a 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);
    }
}

Table Of Contents
10 Data Binding Library
39 ACRA
64 Menu
112 Loader
119 Xposed
132 Colors
135 Fresco
140 AdMob
147 Button
156 Vk SDK
170 XMPP
176 OpenCV
200 FileIO
203 Moshi
217 Paint
231 AIDL
241 JCodec
243 Okio
255 Looper
  ↑ ↓ to navigate     ↵ to select     Esc to close