简体   繁体   中英

How to set OnClickListener on RecyclerView item in MVVM structure

I have an app structured in MVVM . I have different fragments within the same activity. Each fragment has its own ViewModel and all data are retrieved from a REST API.

In FragmentA, there is a RecyclerView that lists X class instances. 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 . 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

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.

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

you can check out my GitHub repository to understand better.

How I imagine it is the following.

The Fragment passes a listener object to the adapter, which in turn passes it to the 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

Hope it is helpful link 1 link 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM