Here is an implementation of OnClickListener for RecyclerView in Kotlin programming language:
class MyAdapter(val context: Context, val itemList: List<String>) : RecyclerView.Adapter<MyAdapter.MyViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val view = LayoutInflater.from(context).inflate(R.layout.my_item_layout, parent, false)
return MyViewHolder(view)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.itemView.setOnClickListener {
Toast.makeText(context, "Item clicked: ${itemList[position]}", Toast.LENGTH_SHORT).show()
}
holder.bind(itemList[position])
}
override fun getItemCount(): Int {
return itemList.size
}
inner class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bind(item: String) {
itemView.itemTextView.text = item
}
}
}
Here, we override the onBindViewHolder()
method to set the OnClickListener for the RecyclerView item. We use the setOnClickListener()
method to set the click listener for the itemView. Inside the click listener, we show a Toast to indicate that the item has been clicked. Finally, we use the inner
keyword to define the MyViewHolder class as an inner class so that we can access the itemList from within the class.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2023-03-08 11:00:00 +0000
Seen: 12 times
Last updated: Mar 14 '22
When the library throws a JsonDataException, why does the Kotlin Moshi adapter return null?
How can Django Admin accommodate a variety of formats and locales for its input fields?
How can an array be passed using typo3 flexform xml and itemsProcConfig?
Is it possible to invoke an asynchronous function without using the await keyword?
How can metadata be linked to a series in Polars?
What is the process of utilizing the map function to map a pandas column using a dictionary?