23

I have a RecyclerView with a working ItemTouchHelper. Everything works great, but I am wondering if there is a way I can detach the ItemTouchHelper from the RecyclerView without re-creating the list? For fun, this is the code I'm using to attach:

ItemTouchHelper.Callback callback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT)
{
    ...
};
mItemTouchHelper = new ItemTouchHelper(callback);
mItemTouchHelper.attachToRecyclerView(mPasswordList);

Ideally, I'd like to check a preference in say onResume() of the Activity this RecyclerView lives in and detach the ItemTouchHelper based on that.

Zain
  • 13,030
  • 5
  • 26
  • 49
nverbeek
  • 1,732
  • 13
  • 17

3 Answers3

28

You can detach the ItemTouchHelper from the RecyclerView by setting recyclerview to null:

mItemTouchHelper.attachToRecyclerView(null);
Andy Cheng
  • 1,027
  • 10
  • 10
  • Nice trick. But, beware of this limitation : https://issuetracker.google.com/issues/37092256 Google claims they fix the bug. However, at the time for this comment being written, the fix isn't released to public yet. – Cheok Yan Cheng Jan 31 '18 at 20:31
  • 1
    @CheokYanCheng, I've checked Android docs, [they say](https://developer.android.com/reference/androidx/recyclerview/widget/ItemTouchHelper#attachToRecyclerView(androidx.recyclerview.widget.RecyclerView)) that `mItemTouchHelper.attachToRecyclerView(null)` can be used for detaching. – Yamashiro Rion Apr 20 '20 at 08:00
24

My original motivation for this was to allow the user the ability to disable swipe actions on list items if they so choose. I assumed the way to do this was to detach the ItemTouchHelper from the RecyclerView. I have now found the ItemTouchHelper.SimpleCallback has the following method available to override:

@Override
public boolean isItemViewSwipeEnabled()
{
    return mSwipable;
}

So, returning the correct state here effectively turns off the swipe handling. I hope this helps someone in the future.

nverbeek
  • 1,732
  • 13
  • 17
0

For me, to disable the entire ItemTouchHelper that attached to the RecyclerView just set it to null

mItemTouchHelper = null;

And to re-enable, set it to its value

mItemTouchHelper = new ItemTouchHelper(callback);
Zain
  • 13,030
  • 5
  • 26
  • 49