Search code examples
androiddata-bindingonclicklistenerandroid-databindingonlongclicklistener

How to add a click and a long click listener on the same view using databinding?


I have this layout file:

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <data class="ItemDataBinding">
        <variable
            name="item"
            type="com.example.data.Item" />

        <variable
            name="onItemClickListener"
            type="com.example.OnItemClickListener" />

        <variable
            name="onLongShoppingListClickListener"
            type="com.example.OnLongItemClickListener" />
    </data>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="@{(v) -> onItemClickListener.onItemClick(item)}">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/item_text_view"
            android:text="@{item.getName()}"/>
    </RelativeLayout>
</layout>

With a single click listener, it works fine. I tried:

android:onClick="@{(v) -> onItemClickListener.onItemClick(item), onLongItemClickListener.onLongItemClick(item)}">

But it doesn't work. How to add both listeners on the same view?


Solution

  • You have to create own ClickHander and use it in XML like below.

        <data>
    
             <variable
                    name="item"
                    type="com.example.data.Item" />
    
            <variable
                name="handler"
                type="embitel.com.databindingexample.helper.ClickHander" />
    
        </data>
    
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onLongClick="@{(v) -> handler.onLongClickOnHeading(v, item)}"
            android:onClick="@{(v)->handler.onItemClicked(v,item)}">
    
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/item_text_view"
                android:text="@{item.getName()}"/>
        </RelativeLayout>
    

    Your ClickHandler class

        public class ClickHander {
    
        public void onItemClicked(View v, Item item) {
            Context context = v.getContext();
            // Your code 
        }
    
        // For long click
        public void onLongClickOnHeading(View v, Item item) {
            Context context = v.getContext();
            // Your code 
        }
    }
    

    set Binding from your Activity or Fragment

    binding.setHandler(new ClickHander());