Databinding in Android

Databinding in Android

Introduction to Android's new databinding Gradle plugin


Bryan Herbst

July 25, 2015


  1. 2.
  2. 3.

    MV[C|P|VM] A Model that represents your raw data. Aka POJOs.

    A View that dictates how your data is displayed to the user Something to get the data and display the view
  3. 5.

    Controller var template = Handlebars.compile(viewTemplate); var data = {title: “Hello

    World", body: “Templating rocks!"}; var html = template(data);
  4. 6.

    Let there be data binding Now we can have better

    separation of concerns Activities and Fragments now have more limited scope and a clearer purpose: ◦ Load data ◦ Bind data to the View ◦ Respond to events
  5. 8.

    The View- step one <?xml version="1.0" encoding="utf-8"?> <layout xmlns:android=""> <LinearLayout

    android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> </LinearLayout> </layout> Wrap your layout in a <layout> tag
  6. 12.

    The controller side @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);

    ActivityAnimalBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_animal); binding.setAnimal(new Elephant()); }
  7. 18.

    NoteViewModel public class NoteViewModel { private static final DateFormat TIMESTAMP_FORMAT

    = DateFormat.getDateInstance(); private Note mNote; public String getFormattedTimestamp() { return TIMESTAMP_FORMAT.format(mNote.getCreatedTime()); } } <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@{note.formattedTimestamp}"/>
  8. 23.

    Observables in the ViewModel public ObservableInt numClicks; public View.OnClickListener clickListener

    = new View.OnClickListener() { @Override public void onClick(View view) { numClicks.set(numClicks.get() + 1); } };
  9. 26.

    Resources Tons of information about: ◦ <include>s ◦ Operators

    in bindings ◦ Accessing arrays/lists/maps ◦ Using resources in bindings ◦ Value converters ◦ Binding custom view properties ◦ More ways to make data observable