Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: How to send data from RecyclerView adapter to a Fragment

I'm new to Android and new to Kotlin (coming from iOS Swift development). I have an activity that has a fragment, inside the fragment is a RecyclerView. When the user taps on a row in the RecyclerView I want to show a dialog and take some action.

In the adapter I have the CustomViewHolder and onClickListener. From there I can capture the row the user tapped on easily. But how do I pass this information back to the fragment so that I can take action / display a dialog?

thanks!

like image 684
FlatDog Avatar asked Sep 12 '25 09:09

FlatDog


1 Answers

Have your adapter take a lambda as a parameter...for example

class YourAdapter(val listener: (YourDataType) -> Unit)

In your view holder you'd then invoke that listener when user clicks on row.

holder.itemView.setOnClickListener { listener(data) }

In your fragment you'd have something like:

    yourAdapter = YourAdapter {
        // invoked when user clicks on row
    }
like image 54
John O'Reilly Avatar answered Sep 14 '25 00:09

John O'Reilly