I have a recycler view, its list is stored in firestore. I want to allow user to reorder the items using drag and drop. When the user removes the hold (drops the item) I want to call the function to update the firestore but whenever the position is changed even while dragging to the desired position the function is getting called. How can I call the function only when the item is placed.
val itemTouchHelper = ItemTouchHelper(
object: ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP or ItemTouchHelper.DOWN, 0){
override fun onMove(
recyclerView: RecyclerView,
source: RecyclerView.ViewHolder,
target: RecyclerView.ViewHolder
): Boolean {
val sourcePosition = source.adapterPosition
val targetPosition = target.adapterPosition
Collections.swap(itemList, sourcePosition, targetPosition)
adapter.notifyItemMoved(sourcePosition, targetPosition)
// Firestore update
updateFirestoreList()
return true
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
TODO("Not yet implemented")
}
})
2
Answers
The way that I achieved it was by overriding the
clearView()
method ofItemTouchHelper
, and calling a callback from it. It would be something like below:The
onItemMovied(from, to)
, is a function in theMyListAdapter
class that is having an implementation like the below:It just updates the list with the new item’s position(you might have a different approach, feel free to use it according to your need or not to use it at all).
And finally, where you are attaching the
MyTouchHelper
, you can use its callback to call your specific function like below:I hope it helps.
When you selected to drag, store this position
When you drop
clearView
will be called, get position of ViewHolder and swap CollectionI hope it helps :))