Home » Android » Android Databinding onLongClick not working

Android Databinding onLongClick not working

Posted by: admin June 15, 2020 Leave a comment

Questions:

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.

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

    <variable
        type="com.aaa.bbb.viewmodel.SystemSettingsViewModel"
        name="systemSettings"
    </variable>
</data>

<TextView
    android:gravity="end"
    android:id="@+id/tv_logging"
    android:layout_centerVertical="true"
    android:layout_height="wrap_content"
    android:layout_marginRight="8dp"
    android:layout_width="wrap_content"
    android:onClick="@{() -> systemSettings.sendLogs()}"
    android:text="@string/enable_logs"
    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.

Answer:

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()}"

Answer:

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 :

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

Answer:

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 { }
}