Android data binding — 2

Binding user event

The first section introduced simple data mapping sample. This section is about event binding

In this example, we add a button in main activity, then handle event when user click on this button

First, in ViewModel, we need define a function to handle event

onClick then will be mapped to layout:

①: Map button text to viewModel. By default (on Android studio designer view, show “Click_Me”)

②: Map onClick event to onClick function of viewModel

That’s it. Now when user click on Button, the Toast will be show.


However, the problem is we wanna separate between ViewModel & View. When user click on Button, 2 separated tasks should be done:

  1. Update some states in ViewModel, and data Model (handle by ViewModel)
  2. Do some task on UI, should handle by View (e.g Toast should be handled by View — activity class)

So we need a method that let View also know about this event.

In this sample, we define ISampleViewModelEventListener as an interface, then when onClick fired, we also call listener.onClickButton(); to raise event to View.

For View class (Activity class in this sample), we implement ISampleViewModelEventListener

And that’s it. If we need more view-model-2-view event, just define more function in ISampleViewModelEventListener.



TOC

Part 1: Binding static value

Part 2: Binding user event

Part 3: EditText & Two-way data binding

Part 4: Sample form data binding