如何使用数据绑定在同一视图上添加点击和长按监听器?

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

我有这个布局文件:

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

使用单击侦听器,它工作正常。我试过了:

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

但是没用。如何在同一个视图中添加两个监听器?

您必须创建自己的 ClickHander 并在 XML 中使用它,如下所示。

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

你的ClickHandlerclass

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

从您的 ActivityFragment

设置绑定
binding.setHandler(new ClickHander());