Search code examples
androidandroid-recyclerviewitemtouchhelper

Restore a swiped view on pressing back button in RecyclerView?


Hi i was following this tutorial here about drag and swipe on a RecyclerView using itemtouchhelper.callback Everything works fine but what if want to restore the view that was swiped out by pressing the backbutton. how it can be done ?


Solution

  • You can store the item which you want restore when you click on the back button. If the object is null, you call the super method else, you add the item in the adapter.

    You need to create a simple interface to get the item swiped.

    In the adapter :

    private OnSwipeListener onSwipeListener;
    
    @Override
    public void onItemDismiss(int position) {
        if (onSwipeListener != null){
          onSwipeListener.onSwipeItem(data.get(position).clone());
        }
        data.remove(position);
        notifyItemRemoved(position);
    }
    

    In the activity :

    T itemSwiped;
    
    // Somewhere after you have created the adapter
    adapter.setOnSwipeListener(new OnSwipeListener(){
       @Override
       public void onSwipeItem(T item){
         itemSwiped = item;
       }
    });
    ...
    Override
    public void onBackPressed() {
        if (itemSwiped == null){ 
          super.onBackPressed()
        } else {
          adapter.addItem(itemSwiped);
        }
    }