简体   繁体   中英

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.

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

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

override fun onBindViewHolder(holder: StPanelHomeViewHolder, position: Int) {
        val item = dataset[position]
        holder.cardViewNavigation[0].setOnClickListener {
            val action =
                StPanelHomeFragmentDirections.actionStPanelHomeFragmentToStPanelPayFeeFragment()
            holder.view.findNavController().navigate(action)
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM