[Android] How to handle onClick event of View in databinding


Writing time : 2021-10-16 12:11:20

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.

Handle one View click event

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  
}  


Handle multiple View click events

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   
    }  
}