Android如何在MVVM架构中处理RecyclerView的点击事件

3

我希望在我的RecyclerView行中处理点击事件,目前通过将Presenter传递给ViewHolder来完成绑定。

Presenter接口:

interface IMainPresenter{
  public void showDetail(Pojo pojo);
}

视图持有者:

class ViewHolder(itemView: View, val parent: ViewGroup?, private val binding: ListMainBinding) : RecyclerView.ViewHolder(itemView) {
            fun bind(pojo: Pojo, mainPresenter: IMainPresenter) {
                binding.pojo = pojo
                binding.mainPresenter = mainPresenter
                binding.executePendingBindings()
            }
        }

在我的布局中,我在onClick属性上调用了我的Presenter的一个方法。

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <data>

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

        <variable
            name="mainPresenter"
            type="com.noisyninja.androidlistpoc.views.main.IMainPresenter" />

        <variable
            name="pojo"
            type="com.noisyninja.androidlistpoc.model.Pojo" />
    </data>

    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/black"
            android:onClick="@{(view) -> mainPresenter.showDetail(pojo)}"
            ...
            ...
            ...

我认为传递Presenter不是一个好的设计,但有什么更好的方法来处理行点击事件并触发Presenter中的方法?


“传递Presenter”为什么不是一个好的设计? - Bink
1个回答

1

我认为更好的方法是像这里那样在RecyclerView中添加OnItemClickListener,然后调用。

ItemClickSupport.addTo(recyclerView).setOnItemClickListener{
        recycler, position, v -> 
        mainPresenter.showDetail(recycler.getAdapter().getItem(position))
}

在设置RecyclerView期间。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接