Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

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.