We will look at two methods of handling the onClick event of View in data binding.
The first way is to handle one View click event in a ViewModel class function.
The second way is to trigger multiple View click events in the ViewModel class function.
In xml, add the code that calls the function of the ViewModel to the onClick property of the View as shown in the code below.
<TextView
android:id="@+id/buttonNext"
android:onClick="@{() -> viewmodel.clickNext()}"
...
/>
In the ViewModel class, create a function without parameters with the name added in the onClick property.
fun clicnNext(){
// TODO
}
In xml, add the code that calls the function of the ViewModel to the onClick property of the View as shown in the code below.
Set the same method to handle click events of multiple views in one method.
<TextView
android:id="@+id/buttonNext"
android:onClick="@{viewmodel.clicnkNext}"
/>
<TextView
android:id="@+id/buttonSave"
android:onClick="@{viewmodel.clicnkNext}"
/>
In the ViewModel class, create a function with the View class parameter with the name added in the onClick property.
Handles View clicks using the passed View ID.
fun clicnNext(view: View){
when(view.id){
R.id.buttonNext -> // TODO
R.id.buttonSave -> // TODO
}
}