Search code examples
androidandroid-recyclerviewgridclickitems

Different onClick for each and every Recyclerview item


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.


Solution

  • 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}
                }
            }
        }
    }