I have a `ViewHolder` class which in charges of po...
# android
a
I have a
ViewHolder
class which in charges of populating the data to the
quote_list.xml
. I create a
setOnClickListener
on the ViewHolder which would call a
QuoteFragment
that populated the relevant data into it. May I know how to populate the data from the
ViewHolder
to the
QuoteFragment
?
Copy code
inner class QuoteViewHolder(private val bindingQuoteListBinding: QuoteListBinding) :
    RecyclerView.ViewHolder(bindingQuoteListBinding.root) {
    fun bind(quote: Quote) {
        // Assign data to the textview
        bindingQuoteListBinding.tvQuote.text = quote.quote
        bindingQuoteListBinding.tvAuthor.text = quote.author ?: "None"

        bindingQuoteListBinding.cardQuote.setOnClickListener {
            val activity = it.context as AppCompatActivity
            val fragment = QuoteFragment()
            fragment.show(activity.supportFragmentManager, "TAG")
        }
    }
}
a
If I understood correct, better pass cosure or juat onClikcListener from fragment -> adapter -> viewholder. and trigger it from VH
val onQuoteClick: (Quote) -> Unit
m
this is what i tend to do as well, just passed down from the fragment when instantiating the adapter
a
Lol, there's this loooooooooooong StackOverflow thread about this and what approaches different people like to take: https://stackoverflow.com/questions/29424944/recyclerview-itemclicklistener-in-kotlin I updated the question to have the current popular approach too. If you really need to handle the click event in the Activity/Fragment, you can pass the function all the way down to the ViewHolder. Or if you don't need access to the Activity/Fragment (maybe in case of using the Navigation library), you can just implement
View.OnClickListener
in the ViewHolder and use
itemView.setOnClickListener(this)
in the
init
block