I have got a list of simple items in RecyclerView. Using ItemTouchHelper it was very easy to implement \"swipe-to-delete\" behavior.
public class TripsAdapte
I agree with @Gabor that it is better to soft delete the items and show the undo button.
However I'm using Snackbar for showing the UNDO. It was easier to implement for me.
I'm passing the Adapter and the RecyclerView instance to my ItemTouchHelper callback. My onSwiped is simple and most of the work is done by adapter.
Here is my code (edited 2016/01/10):
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
mAdapter.onItemRemove(viewHolder, mRecyclerView);
}
The onItemRemove methos of the adapter is:
public void onItemRemove(final RecyclerView.ViewHolder viewHolder, final RecyclerView recyclerView) {
final int adapterPosition = viewHolder.getAdapterPosition();
final Photo mPhoto = photos.get(adapterPosition);
Snackbar snackbar = Snackbar
.make(recyclerView, "PHOTO REMOVED", Snackbar.LENGTH_LONG)
.setAction("UNDO", new View.OnClickListener() {
@Override
public void onClick(View view) {
int mAdapterPosition = viewHolder.getAdapterPosition();
photos.add(mAdapterPosition, mPhoto);
notifyItemInserted(mAdapterPosition);
recyclerView.scrollToPosition(mAdapterPosition);
photosToDelete.remove(mPhoto);
}
});
snackbar.show();
photos.remove(adapterPosition);
notifyItemRemoved(adapterPosition);
photosToDelete.add(mPhoto);
}
The photosToDelete is an ArrayList field of myAdapter. I'm doing the real delete of those items in onPause() method of the recyclerView host fragment.
Note edit 2016/01/10: