1

Currently,, I am designing shopping cart...I had used recycler view to all display items,,, and also I had add to cart button in Recycler view ,,,whenever user clicks that add to cart button then I want to increment the count of total item (total count button is present outside the Recycler view in the fragment ) How can I send count value(Added to cart value) from Recycler view to that fragment....please help me . I am new to android

class Myadapter: RecyclerView.Adapter<Myadapter.MyViewHolder>() {
 var items=ArrayList<Data>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
    return MyViewHolder(LayoutInflater.from(parent.context).
    inflate(R.layout.new_resource,parent,false))
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
   var image=view.image
   var Addtocart=view.Addtocart
   
 Addtocart.setOnClickListener{
 count++

}
}
override fun getItemCount(): Int {
   return items.size
}
 fun setListData(data:ArrayList<Data>){
this.items=data

}

  • 1
    You need to use a callback by constructor in the adapter to notify to the viewModel that the viewHolder it was clicked. The ViewModel receive the notification to set the count cart livedata value (for example, updateCartCounterLiveData) and the fragment update your badge counter cart. How to create a callback? the solution is in stackoverflow https://stackoverflow.com/questions/32720702/how-to-call-a-mainactivity-method-from-viewholder-in-recyclerview-adapter – Manuel Mato Nov 27 '20 at 08:04

1 Answers1

1

You can try this code:

class MainFragment : Fragment() {

    private val adapter by lazy {
        MainAdapter(
            ::yourFun
        )
    }
    
    fun yourFun (itemPosition: Int) {
        
    }
}

Recycler:

class MainAdapter(private val yourFun: (itemPosition: Int) -> Unit) : RecyclerView.Adapter<Myadapter.MyViewHolder>() {

// other code

inner class ItemViewHolder(item: View) : RecyclerView.ViewHolder(item) {

            // other code

            setOnClickListener { yourFun(position) }
        }
    }
Simon Mayrshofer
  • 1,264
  • 1
  • 11
  • 18
Alesh17
  • 366
  • 1
  • 7