【问题标题】:Android how to handle recyclerview clicks in mvvm architectureAndroid如何处理mvvm架构中的recyclerview点击
【发布时间】:2018-07-16 18:54:46
【问题描述】:

我想处理我的 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)}"
            ...
            ...
            ...

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

【问题讨论】:

  • 为什么“通过演示者”不是一个好的设计?

标签: android mvvm android-recyclerview android-databinding android-mvvm


【解决方案1】:

恕我直言,更好的方法是将 OnItemClickListener 添加到 RecyclerView,如 here,然后调用

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

在设置 RecyclerView 期间。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-18
    • 2023-03-22
    • 2017-07-30
    • 2019-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多