提问者:小点点

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


我有这个布局文件:

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

但不管用。 如何在同一视图上添加两个侦听器?


共1个答案

匿名用户

您必须创建自己的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>

您的ClickHandler

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

activity片段设置绑定

binding.setHandler(new ClickHander());

相关问题