Search code examples
androidkotlinandroid-databindinghigher-order-functionsandroid-binding-adapter

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?


Solution

  • Switching from hoc func to the the listener of this custom view worked for me:

    import com.synnapps.carouselview.ImageClickListener
    
    @BindingAdapter("onClick")
    fun setOnClick(carouselView: CarouselView, imageClickListener: ImageClickListener) {
        carouselView.setImageClickListener(imageClickListener)
    }