Android Databinding onLongClick not working

I managed to work it correctly. I doubt this is properly documented.

In xml

android:onLongClick="@{(view) -> presenter.onLongClickOnHeading(view)}"

In presenter viewmodel class

public boolean onLongClickOnHeading(View v) { 
   //logic goes here
   return false; 
}

Note: this method signature should be exactly in this format. Otherwise biding errors will be thrown at runtime.


Here is the complete the code.

There is no such attribute for long click. So we have to create a binding adapter.

BindingUtils.kt

object BindingUtils {

    private const val ON_LONG_CLICK = "android:onLongClick"

    @JvmStatic
    @BindingAdapter(ON_LONG_CLICK)
    fun setOnLongClickListener(
        view: View,
        func : () -> Unit
    ) {
        view.setOnLongClickListener {
            func()
            return@setOnLongClickListener true
        }
    }
}

Layout

<androidx.constraintlayout.widget.ConstraintLayout
    android:background="?android:attr/selectableItemBackground"
    android:clickable="true"
    android:focusable="true"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="10dp"
    android:onLongClick="@{() -> vm.onLongClick()}"/>