Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
this is my code ... i want set on click listener for each item in recycelrview but it didn't work well

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {

    val layoutview =
        LayoutInflater.from(parent.context).inflate(R.layout.product_items, parent, false)
    val vh = ViewHolder(layoutview)

    vh.itemView.setOnClickListener {
        val pos = vh.adapterPosition

            val activity = it.context as AppCompatActivity

            val bundle = Bundle()

            val myFragment = ItemDetailsfragment()
            myFragment.arguments = bundle

            val productitem = product[pos]

            bundle.putString("title", productitem.title)

            bundle.putString("price", productitem.price.toString())

            bundle.putString("image", productitem.image.toString())

            activity.supportFragmentManager.beginTransaction()
                .replace(R.id.homepage, myFragment)
                .addToBackStack(null)
                .commit()


        }

    return vh


}


What I have tried:

from on BindViewHolder i can do this and click on items but the issue on the BindViewHolder is when i click on everywhere on recyclerview screen it goes to items and this is not good ... so is say maybe it work on onCreateViewHolder
Posted
Comments
Sandeep Mewara 18-Aug-20 13:10pm    
Do share if these help:
https://stackoverflow.com/questions/35584584/recyclerview-onclick-not-working
https://stackoverflow.com/questions/39974257/onclicklistener-doesnt-work-with-recyclerview-items
https://antonioleiva.com/recyclerview-listener/
David Crow 18-Aug-20 13:34pm    
I did it this way:

@Override
public void onBindViewHolder(ViewHolder holder, int position)
{
    ...
    holder.itemView.setTag(array.get(position));
    holder.itemView.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick( View view )
        {
            ItemDetails details = (ItemDetails) view.getTag();
            ...
        }
    });
}

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900