Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Databinding in Android

Databinding in Android

Introduction to Android's new databinding Gradle plugin

Bryan Herbst

July 25, 2015

More Decks by Bryan Herbst

Other Decks in Programming


  1. 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
  2. Controller var template = Handlebars.compile(viewTemplate); var data = {title: “Hello

    World", body: “Templating rocks!"}; var html = template(data);
  3. 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
  4. The View- step one <?xml version="1.0" encoding="utf-8"?> <layout xmlns:android="http://schemas.android.com/apk/res/android"> <LinearLayout

    android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> </LinearLayout> </layout> Wrap your layout in a <layout> tag
  5. 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()); }
  6. 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}"/>
  7. 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); } };
  8. Resources https://developer.android.com/tools/data-binding/guide.html 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