How do i bind and invoke`function type` in android data binding?
The way I went about it is as follows. The method you have will correspond to the class kotlin.jvm.functions.Function1
. so the idea is to declare this in the XML as such:
<data>
<import type="kotlin.jvm.functions.Function1"/>
<import type="kotlin.Unit"/>
<variable
name="theMethod"
type="Function1<Integer, Unit>"/>
</data>
It doesn't look pretty, but it works. We import what we want and then declare a binding variable of the type we want. Note that the character <
is illegal when trying to define generic types, so we use <
.
Now it should be easy to use. I do it like:
android:onClick="@{_ -> theMethod.invoke(someInt)}"
The method signature for onClick
requires us to pass in a method that receives one parameter of type View
. I'm not interested in using it, so I declare it as _
in the lambda I pass to the onClick
. Then inside the lambda I invoke the method I want.
I always make an effort not to put logic inside the XML, but I allow myself these kind of shortcuts, since I don't really think of them as business logic.
Hope it helps.
Use the lambda form
android:onClick="@{() -> theMethod.invoke(someInt)}