[英]How to set OnClickListener on RecyclerView item in MVVM structure
I have an app structured in MVVM
. 我有一个在
MVVM
构建的应用程序。 I have different fragments within the same activity. 我在同一活动中有不同的片段。 Each
fragment
has its own ViewModel
and all data are retrieved from a REST API. 每个
fragment
都有自己的ViewModel
并且所有数据都是从REST API检索的。
In FragmentA, there is a RecyclerView
that lists X class instances. 在FragmentA中,有一个
RecyclerView
列出了X个类实例。 I want to set OnClickListener
on the RecyclerView
and I want to pass related X object to FragmentB
when an item clicked in the RecyclerView
. 我想在
RecyclerView
上设置OnClickListener
,并且要在RecyclerView
单击某个项目时将相关的X对象传递给FragmentB
。 How can I achieve this? 我该如何实现?
if you're using data binding you need to pass your view(which is Fragment in your case) into the layout via adapter class and you need to import your view in layout file to be able to call view's method 如果您使用数据绑定,则需要通过适配器类将视图(在您的情况下为Fragment)传递到布局中,并且需要将视图导入布局文件中才能调用视图的方法
android:onClick="@{() -> view.onXXXClick(item)}"
pass your current model class which is item
into this new method and then create onXXXClick method in your view and do whatever you wish. 将当前作为
item
模型类传递到此新方法中,然后在视图中创建onXXXClick方法并执行所需的任何操作。
if you will be doing view related operations such as navigation from one fragment to another or starting a service you should create above function in your view, if you're doing network or db related operations it should be in your ViewModel
如果要执行与视图相关的操作,例如从一个片段导航到另一个片段或启动服务 ,则应在视图中创建上述功能;如果要进行与网络或数据库相关的操作,则应在
ViewModel
you can check out my GitHub repository to understand better. 您可以查看我的GitHub存储库以更好地了解。
How I imagine it is the following. 我的想象如下。
The Fragment passes a listener object to the adapter, which in turn passes it to the ViewHolders 片段将侦听器对象传递给适配器,适配器又将其传递给ViewHolders
Here is a quick sketch of how it should look like 这是一个简短的草图
class Fragment {
val listener = object: CustomAdapter.CustomViewHolderListener() {
override fun onCustomItemClicked(x: Object) {}
}
fun onViewCreated() {
val adapter = CustomAdapter(listener)
}
}
---------------
class CustomAdapter(private val listener: CustomViewHolderListener) {
val listOfXObject = emptyList() // this is where you save your x objects
interface CustomViewHolderListener{
fun onCustomItemClicked(x : Object)
}
override fun onBindViewHolder(holder: CustomViewHolder, position: Int) {
holder.itemView.setOnClickListener {
listener.onCustomItemClicked(listOfXObject[position])
}
}
}
Here are some articles that might help you get the general gist of the things. 这里有一些文章可能会帮助您了解这些事情的基本内容。 They don't answer your question directly though
他们虽然没有直接回答您的问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.