首页 > 解决方案 > Android如何处理mvvm架构中的recyclerview点击

问题描述

我想处理我的 recyclerview 行中的点击,并且当前将我的演示者传递给我的视图绑定。

演示者界面:

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 属性上调用了我的演示者的方法

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

我认为传递演示者不是一个好的设计,但是有什么更好的方法来处理从在我的演示者中触发一个方法的行的点击?

标签: androidmvvmandroid-recyclerviewandroid-databindingandroid-mvvm

解决方案


恕我直言,更好的方法是像这里OnItemClickListener一样添加到 RecyclerView ,然后调用

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

在设置 RecyclerView 期间。


推荐阅读