I've a variable of type (position: Int) -> Unit
and I want to invoke the method from xml like this android:onClick="@{theMethod.invoke(someInt)}
Is it possible?, then How can I do it ?
In Android, the Data Binding Library is a support library that allows you to bind UI components in your layouts to data sources in your app using a declarative format rather than programmatically.
View Binding Part of Android Jetpack. View binding is a feature that allows you to more easily write code that interacts with views. Once view binding is enabled in a module, it generates a binding class for each XML layout file present in that module.
Note: The Data Binding Library generates a class named BR in the module package which contains the IDs of the resources used for data binding. In the example above, the library automatically generates the BR. item variable.
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)}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With