Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 679
Mehmed Avatar asked Aug 21 '19 07:08

Mehmed


1 Answers

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

like image 87
john-salib Avatar answered Nov 15 '22 05:11

john-salib