Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i bind and invoke`function type` in android data binding?

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 ?

like image 932
theapache64 Avatar asked Feb 20 '19 04:02

theapache64


People also ask

What are the data binding types in Android?

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.

What does bind mean in Android?

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.

What is Br in data binding Android?

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.


2 Answers

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&lt;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 &lt;.

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.

like image 94
Fred Avatar answered Oct 12 '22 19:10

Fred


Use the lambda form

android:onClick="@{() -> theMethod.invoke(someInt)}
like image 41
Ge3ng Avatar answered Oct 12 '22 19:10

Ge3ng