Search code examples
androidkotlinlistadapter

ListAdapter: grab item or itemPos in fragment


I have the following fragment which has a RecyclerView and a ListAdapter of users:

....
private fun setupList(users: List<User>) {
    recyclerView.layoutManager = LinearLayoutManager(context, RecyclerView.VERTICAL, false)
    val adapter = UsersAdapter {
        Toast.makeText(context, "Clicked", Toast.LENGTH_SHORT).show()
    }

    recyclerView.adapter = adapter
    adapter.submitList(users)
}
....

Here is the relevant part of the UsersAdapter:

....
class FlightItemViewHolder(itemView: View, _context: Context) : RecyclerView.ViewHolder(itemView) {
    val context = _context

    fun bind(item: User, clickListener: (User) -> Unit) {

        itemView.name_value.text = item.fullName
        itemView.country_value.text = item.country
        itemView.seats_value.text = item.subscriptionSeats.toString()

        itemView.setOnClickListener { clickListener(item) }
    }
}
....

The toast is showing fine, but I would like to get a hold of the clicked element or its position in order to call and show a Detail fragment (instead of showing the toast).


Solution

  • you have to change your callback to like that

    val adapter = UsersAdapter { user ->
        Toast.makeText(context, "Clicked $user", Toast.LENGTH_SHORT).show()
    }