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.
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.
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
Run the app, it works now. You can see Albert on the screen
Let’s see you want to bind a
onClick for a button.
- You need the
onClick needs to have according signature:
- You don’t need that
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.
Hope it helps.