Is there a way to revert a swipe action and restore the view holder to its initial position after the swipe is completed and onSwiped
is called
A dirty workaround solution for this problem is to re-attach the ItemTouchHelper by calling ItemTouchHelper::attachToRecyclerView(RecyclerView)
twice, which then calls the private method ItemTouchHelper::destroyCallbacks()
. destroyCallbacks()
removes item decoration and all listeners but also clears all RecoverAnimations.
Note that we need to call itemTouchHelper.attachToRecyclerView(null)
first to trick ItemTouchHelper
into thinking that the second call to itemTouchHelper.attachToRecyclerView(recyclerView)
is a new recycler view.
For further details take a look into the source code of ItemTouchHelper
here.
Example of workaround:
RecyclerView recyclerView = findViewById(R.id.recycler_view);
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(callback);
...
// Workaround to reset swiped out views
itemTouchHelper.attachToRecyclerView(null);
itemTouchHelper.attachToRecyclerView(recyclerView);
Consider it as a dirty workaround because this method uses internal, undocumented implementation detail of ItemTouchHelper
.
Update:
From the documentation of ItemTouchHelper::attachToRecyclerView(RecyclerView)
:
If TouchHelper is already attached to a RecyclerView, it will first detach from the previous one. You can call this method with null to detach it from the current RecyclerView.
and in the parameters documentation:
The RecyclerView instance to which you want to add this helper or null if you want to remove ItemTouchHelper from the current RecyclerView.
So at least it is partly documented.
With the latest anndroidX packages I still have this issue, so I needed to adjust @jimmy0251 solution a bit to reset the item correctly (his solution would only work for the first swipe).
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
clipAdapter.notifyItemChanged(viewHolder.adapterPosition)
itemTouchHelper.startSwipe(viewHolder)
}
Note that startSwipe()
resets the item's recovery animations correctly.