Boil Boilerplate Code with Data Binding
Data Binding is a great utility in Android. It helps us extract all the UI related code and keep our classes clean. All the code pertaining to UI resides inside the “declarative” layouts and hence the glue code logic is minimized.
Here is a common use case where we want to create a login form in which the Login Button gets enabled only when the email and password fields are set. Following is a visual representation for the same:
The usual and more insipid solution will be to use TextWatcher
to watch the text as and when it changes and design some logic accordingly. With 2-way Data Binding, it’s only a play of a few lines. ThenotifyPropertyChanged
helps us get the callbacks from different elements. Show me the code! Ok 👇🏻
1. Enable Data Binding
In your app-level build.gradle
, enable Data Binding
android {
....
dataBinding {
enabled = true
}
}
2. Create a View Model
3. Create a Handler
Create a Handler
interface for the onClick
callback which we can implement in our Activity/Fragment.
4. Bind in XML Layout
5. Instantiate in View
Lets connect all the dots. In your View (Activity/Fragment), instantiate binding
and set theViewModel
and Handler
.
Unlike RxBindings, this approach is pretty straight forward and simple. You can also use ObservableField<T> alternatively if you don’t want to extend BaseObservable. If this post made you happy , you can sing the Pharrell Williams song and clap along 👏🏻😊