Support for two-way data binding was recently added to Android data binding. This is an investigation into using data binding with ViewModels
.
- View Models: Data binding is a natural fit. Declare your ViewModel as a variable in the layout file and bind to its properties.
- Type Safe:
No more
findViewById
or casting views. - View Holder:
A Binding class is auto-generated from your layout file during the processing step. It acts as a
view holder
and providing convenient access to them. Any view that has an id will have a field in the generated binding class. - Reduce Boilerplate: A lot of boilerplate code gets eliminated.
- Null Safe: Failure is graceful. If the bound object or fields have a null value, no worries. The library uses the default value of the field based on its type, in the case of a String this is null. This can clean up the lots of null checks.
- Performance:
Data binding is faster than
findViewById
becuase it is processed once. When you runfindViewById
, the view hierarchy is walked each time to find it - Included Layouts: Passing variable to included layouts is supported.
- Backwards Compatibility: Because the layout files are processed and scrubbed before compile, data binding is supported all the back to Android 2.1 (API level 7+).
- Custom bindings Binding adapters allow you to set any property of a view including custom attributes you create.
- Expressions in XML layouts: Complex expressions are supported. But this is a pretty bad idea.
- Coding by convention: Uses POJO naming conventions.
- it may not be immediately obvious from the official docs but you really must:
- extend
BaseObservable
- explicitly fire property change events in your setters
- annotate your getters with
@Bindable
to generate a resource to refer to innotifyPropertyChanged(BR.<propertyName>
- extend
- potential for name collisions
- ran into a collision in the auto-getnerated code due to 20-char limit
- fixed for AS 2.3: https://code.google.com/p/android/issues/detail?id=212492
- build problems with Android Studio
- try 'Invalidate Caches': Always worth a try, but it doesn't always solve the issue.
- recommend the 'android-apt' plugin: This helps Android Studio pickup code generated by the annotation processor.
Tell Gradle to enable data binding:
// build.gradle android { ... dataBinding.enabled = true }
Wrap layout file contents in a tag:
Add binding expressions (one-way) using the “@{…}” format.
Thare are a number of good blog tutorials.
Very proming but not ready. Review again in a few months after bugs in the tooling are ironed out.