How to use data binding for Switch onCheckedChageListener event?

Mohanish Nerurkar picture Mohanish Nerurkar · May 17, 2016 · Viewed 25k times · Source

As question indicates, how to bind checked change listener to Switch button in xml ?

I am not using recycler view. Just a simple layout.

Any help appreciated.

Answer

tomrozb picture tomrozb · Oct 3, 2016

Using lambda expression and a Switch:

public void onCheckedChanged(boolean checked) {
     // implementation      
}

XML file:

<android.support.v7.widget.SwitchCompat
    android:onCheckedChanged="@{(switch, checked) -> item.onCheckedChanged(checked)}"
    ...
/>

Where item is the class that implements onCheckedChange method and is imported to the XML file like this:

<data>
    <variable
        name="item"
        type="yourClass"/>
</data>