Minimal Android MVVM Databinding Setup with Kotlin
Databinding for MVVM or any other pattern is a must have. Let’s see how to set it up. The reason for this blog is that it seems most of the examples out there online either deprecated or just try to solve another problem. Our goal is to setup a project with a brand new project generated from Android Studio.
First thing first, creating a new project from Android Studio.
1. Add dependencies to your build.gradle
1 | apply plugin: 'kotlin-kapt' |
2. Write a view model for the main activity
1 | import android.arch.lifecycle.ViewModel |
3. Add the view model to the XML
1 |
|
Something you need to aware is that <data>
is in the <layout>
. Which means you need to add it to the XML
, because it is not there.
4. Add the connection in the MainActivity.kt
1 | import xyz.akbertgao.mvvmdatabindingexample.databinding.ActivityMainBinding |
What happens so far? In step 3, we use that viewModel
variable in XML to do the binding. But it hasn’t been initialized yet. So here, we first setup the binding, then populate the binding.viewModel
with an actual instance of the MainViewModel
.
Run the app, it works now. You can see Albert on the screen
5. What about bind an event handler
Let’s see you want to bind a onClick
for a button.
- You need the
view:View
as parameter
1 | <button |
onClick
needs to have according signature: fun onClick(view:View)
- You don’t need that
view:View
as parameter
1 | <button |
The syntax here is just a lambda which wraps the method from view model which makes it very flexible. You can actually pass anything you want to the handler.
6. What about visibility
1 | <data> |
7. End
Hope it helps.
Thanks for reading!
Follow me (albertgao) on twitter, if you want to hear more about my interesting ideas.