Data binding in Android

posted in: Android, Guides, Mobile | 0

Warning: as of june 2015 the Android data binding library is in beta. Some part of this article may become obsolete with time but main concept will still be valid I guess.

android_evolve

What is data binding?

If you have already used some modern JS frameworks such as Angular.js, Ember.js Knockout.js or Backbone.js you should already be familiar with UI data binding. Otherwise here is a short overview.

If you have a user interface  showing information about an object with for example few text fields (eg: name, lastname, age..). The first long thing you have to do is in the onCreateView set the text for the differents TextView or other UI elements. With data binding you can directly link your UI element with values from your model properties. You can also let your UI directly update your UI when you modify the properties of the object.

 

For a brief example in AngularJS you should look this.

Installing

 

Just update your gradle build file with:

 

How it works?

When you design your XML layout, you have to define in the root of your layout, which model your layout will use for databinding.

 

After in your layout, you can access the properties of your object like this for example:

Your song object can be in two different formats, an object with the used properties set as public or an object with correct getters.

 

Updating the view with changed properties

Imagine if we want to update a field like the artist and we want the change to be visible on the UI. It’s pretty simple and straightforward as we use the Java Observer patern.

First you hav to exend your objec to a  BaseObservable and add in the getters and setters the  notifyPropertyChanged  Add the Bindable  property to the getters.

 

In order for it to work, you’ll have to generate a binding when you setup your view.

I guess we are all set!

 

Conclusion

This new Android tool seems really handy to develop apps faster and in a more reliable and maintainable way that we never add before!

Here is the official guide from android developpers!

Leave a Reply