Home > other >  How to pass data from adapter to fragment using ItemTouchHelper.SimpleCallback
How to pass data from adapter to fragment using ItemTouchHelper.SimpleCallback

Time:08-17

I have a RecyclerView where I display my data and I have an ItemTouchHelper to swipe to delete my data. All works good with this but what I'm to do is to pass a variable from adapter to use it in onSwiped method of ItemTouchHelper.SimpleCallback in fragment. Any idea?

I'm using Paging 3 library to show my data.

This is what I tried:

ItemTouchHelperSwipe

class ItemTouchHelperSwipe(private val swipeItemTouchListener: SwipeItemTouchListener): ItemTouchHelper.SimpleCallback(0,ItemTouchHelper.LEFT){
     override fun onSwiped(viewHolder:RecyclerView.ViewHolder,direction:Int)  {
        swipeItemTouchListener.onSwiped(viewHolder,direction)    
      }
      //More overrided method...
}

SwipeItemTouchListener interface:

interface SwipeItemTouchListener{
    fun onSwiped(holder:RecyclerView.ViewHolder?,direction:Int)
    //More functions...
}

Fragment

class MyFragment : Fragment(),SwipeItemTouchListener{
   override fun onSwiped(holder:RecyclerView.ViewHolder?,direction:Int?){
       //Here is where I want to use the variable from adapter
   }
}

Adapter (using PagingDataAdapter from Paging 3 library)

class MyAdapter : PagingDataAdapter<MyModel, RecyclerView.ViewHolder>(ModelComparator){
    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int){
        val mymodel : MyModel? = getItem(position)
        val mymodelID = mymodel.data.id  //This id is what I want to pass to fragment
    }
}

CodePudding user response:

        override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
            val position = viewHolder.absoluteAdapterPosition
            val item = mAdapter.snapshot().items[position]

            // use your item id

        }
  • Related