android - 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)}"
...
...
...
我认为传递演示者不是一个好的设计,但是有什么更好的方法来处理从在我的演示者中触发一个方法的行的点击?
解决方案
恕我直言,更好的方法是像这里OnItemClickListener
一样添加到 RecyclerView ,然后调用
ItemClickSupport.addTo(recyclerView).setOnItemClickListener{
recycler, position, v ->
mainPresenter.showDetail(recycler.getAdapter().getItem(position))
}
在设置 RecyclerView 期间。
推荐阅读
- macos - 在我的 iMac 上升级到 Big Sur 后无法运行 gfortran
- nuxt.js - 在 Vuex State 中访问 Nuxt `$config`
- logging - Kedro:在管道中按命名空间保存日志消息
- javascript - Discord Bot 将用户与语音通道断开连接
- github - Git 获取显式提交的标签
- javascript - 如何创建提亮框内容?
- powershell - 无法导出 Powershell 结果
- testing - 带有 this.* 的赛普拉斯访问别名不起作用
- indexing - awk - 打印包含在初始分析中找到的最大值的所有行(行间包含 U+2500 Unicode 字符)
- javascript - React - 在 Map() 方法中对表列进行排序