Home > Enterprise >  Different onClick for each and every Recyclerview item
Different onClick for each and every Recyclerview item

Time:03-14

I am making a grid layout with the help of Recyclerview and I have already added four Recyclerview items in a grid programmatically and now I want to navigate to different fragments when I click on different items. I am unable to find any appropriate way to do so.

CodePudding user response:

Try below code

override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        holder.textViewName.text = seriesList[position].name
        holder.textViewNameDesc.text = seriesList[position].desc

        holder.textViewName.setOnClickListener {
                            Toast.makeText(context,"clicked",Toast.LENGTH_SHORT).show()
        }


    }

You need to add above code in your recycler adapter

CodePudding user response:

You should use if condition in onBindViewHolder of your adpter class as bellow:

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    holder.item.setOnClickListener {
        when (position) {
            0 -> {
                //navigate to first fragment}
            }
            1 -> {
                //navigate to second fragment}
            }
            2 -> {
                //navigate to third fragment}
            }
            3 -> {
                //navigate to fourth fragment}
            }
        }
    }
}
  • Related