Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Higher order function in BindingAdapter

I am using DataBinding in android and I have a custom view: CarouselView

I wrote a binding adapter for that:

@BindingAdapter("onClick")
fun setOnClick(carouselView: CarouselView, onClick: (position: Int) -> Unit) {
    carouselView.setImageClickListener { position ->
        onClick.run(position)
    }
}

And in the xml:

<com.synnapps.carouselview.CarouselView
            android:id="@+id/carouselView"
            ...
            app:onClick="@{(p) -> vm.onAdsClicked(p)}"/>

But it does not compile. So I saw this answer in the Stackoverflow. But my problem is that I cannot use Runnable instead of kotlin hoc function because I need to pas a parameter to function.

How can I solve that?

like image 388
Saman Sattari Avatar asked Apr 09 '26 15:04

Saman Sattari


1 Answers

If I may, I had the same issue (passing a param inside a HOF in a BindingAdapter) and came up with a more elegant solution. You can indeed make this work, you just need define the HOF as a variable first.

ViewModel:

val onAdsClicked = fun(position: Int) {
// Do stuff
}

XML:

<com.synnapps.carouselview.CarouselView
            android:id="@+id/carouselView"
            ...
            app:onClick="@{vm.onAdsClicked}"/>

BindingAdapter:

@BindingAdapter("onClick")
fun setOnClick(carouselView: CarouselView, onClick: (position: Int) -> Unit) {
    carouselView.setImageClickListener { position ->
        onClick(position)
    }
}
like image 191
Bogdan Zurac Avatar answered Apr 12 '26 05:04

Bogdan Zurac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!