Home » Android » Android Databinding onLongClick not working

Android Databinding onLongClick not working

Posted by: admin June 15, 2020 Leave a comment


I have a text view to which I need to create a listener for onLongClick.
Right now for the respective viewmodel it has a function sendLogs() which deals with the logic for onClick. If I change onClick to onLongClick function never get call. Is there any way to make it work for onLongClick?

onClick is directly linked to my model class function but not the onLongClick. So I think model class binding is correct but I may need some extra work here.

    <import type="android.view.View" />


    android:onClick="@{() -> systemSettings.sendLogs()}"
    android:textAlignment="viewEnd" />
How to&Answers:

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.


You should look into this document

OnLongClick is as easy as onClick

Within your SystemSettingsViewModel you can have

public boolean onLongClick(){}

and in xml

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


For it to work, the part in parenthesis has to match the method signature from the interface View.OnLongClickListener which looks like this :

boolean onLongClick(View view);

So this is how I got it to work :

android:onLongClick="@{(view) -> listener.onLongClick(view, viewmodel)}"/>


As mentioned in the Google documentation Link there is no problem with what you wrote.

This is a sample of OnLongClick in XML:

android:onLongClick="@{(theView) -> presenter.onLongClick(theView, task)}"

class Presenter {
    fun onLongClick(view: View, task: Task): Boolean { }