I am trying to bind the following elements:
xml:
<android.support.v7.widget.SwitchCompat
...
bind:onCheckedChanged="@{(isChecked) -> viewModel.onCheckedChanged(isChecked)}"
.../>
viewModel:
class MyViewModel() {
fun onCheckedChanged(isChecked: Boolean) {
...
}
}
using a BindingAdapter:
@BindingAdapter("onCheckedChanged")
fun bindOnCheckedChanged(view: SwitchCompat, onCheckedChanged: (Boolean) -> Unit) {
view.setOnCheckedChangeListener(
{ _, isChecked ->
if (view.isPressed) onCheckedChanged(isChecked)
}
)
}
The error I get is this one:
data binding error ****msg:cannot find method onCheckedChanged(java.lang.Object) in class MyViewModel
It seems that the data binder does not recognize isChecked
as a Boolean
. I tried to force the typing in the xml like isChecked:Boolean
but I get a bunch of different errors.
Right now I made it work by using Any
instead of Boolean
but I feel like it's wrong:
@BindingAdapter("onCheckedChanged")
fun bindOnCheckedChanged(view: SwitchCompat, onCheckedChanged: (Any) -> Unit) {
...
and
fun onCheckedChanged(isChecked: Any) {
val isSwitchChecked = isChecked as? Boolean ?: return
...
Does anyone know how to make it work the correct function signature?