Skip to content

Instantly share code, notes, and snippets.

@Alqueraf
Last active October 15, 2020 14:55
Show Gist options
  • Save Alqueraf/c308812a356f7b025b54327efae94b72 to your computer and use it in GitHub Desktop.
Save Alqueraf/c308812a356f7b025b54327efae94b72 to your computer and use it in GitHub Desktop.
Adapter Click Listener Example
// Pass a click "listener" lambda function as a parameter
class Adapter(
private val clickListener: (item: Item) -> Unit,
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
// Adapter code here ...
override fun onBindViewHolder(viewHolder: RecyclerView.ViewHolder, position: Int) {
// Get Current Item
val item = list[position]
// Set Click Listener
view.setOnClickListener {
// Invoke our click listener
clickListener(item)
}
}
}
// In the Activity or Fragment, create the Adapter with the Click Listener you want
val adapter = Adapter(...) { item ->
// Here you can startActivity or use any context-related action you may need
startActivity(...)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment