David Green
David Green

Reputation: 83

how can I get row Id or item position from recyclerview when it is clicked in Kotlin

I have recyclerView_main in my main_activity.xml which is holding single_row.xml in Kotlin project.

recyclerView_main is filled up with multiple rows from database.

I need to get the row ID, or position whenever I click a specific row.

is there a way to do that?

I have buttons on that row and if type setOnClickListener() there is no option for getPosition() or getId()

is there a method to do this or I am missing something here?

Thanks

Upvotes: 0

Views: 730

Answers (2)

PhillauSofia
PhillauSofia

Reputation: 381

What do you mean by the fact that you need to acces the id from the main_activity? When you create the adapter, you also define the onClick function that you'll use in the onBindViewHolder() method.

val onClick = {movie: Movie -> doSomethingWithTheId(movie.id)} 
val adapter = MoviesAdapter(movies, rowLayout, context, onClick)

Upvotes: 0

Are you using an Adapter to handle that recyclerview? Inside adapter is the place where you bind each item, there you will have and onBindViewHolder function that receives position and you can set a 'setOnClickListener' there.

Here is an example code implementing a adapter: RecyclerView Adapter Check the onBindViewHolder there

Upvotes: 1

Related Questions