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
The usual approach is not to delete the item immediately upon swipe. Put up a message (it could be a snackbar or, as in Gmail, a message overlaying the item just swiped) and provide both a timeout and an undo button for the message.
If the user presses the undo button while the message is visible, you simply dismiss the message and return to normal processing. Delete the actual item only if the timeout elapses without the user pressing the undo button.
Basically, something along these lines:
@Override
public void onSwiped(final RecyclerView.ViewHolder viewHolder, int direction) {
final View undo = viewHolder.itemView.findViewById(R.id.undo);
if (undo != null) {
// optional: tapping the message dismisses immediately
TextView text = (TextView) viewHolder.itemView.findViewById(R.id.undo_text);
text.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
callbacks.onDismiss(recyclerView, viewHolder, viewHolder.getAdapterPosition());
}
});
TextView button = (TextView) viewHolder.itemView.findViewById(R.id.undo_button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
recyclerView.getAdapter().notifyItemChanged(viewHolder.getAdapterPosition());
clearView(recyclerView, viewHolder);
undo.setVisibility(View.GONE);
}
});
undo.setVisibility(View.VISIBLE);
undo.postDelayed(new Runnable() {
public void run() {
if (undo.isShown())
callbacks.onDismiss(recyclerView, viewHolder, viewHolder.getAdapterPosition());
}
}, UNDO_DELAY);
}
}
This supposes the existence of an undo
layout in the item viewholder, normally invisible, with two items, a text (saying Deleted or similar) and an Undo button.
...
Tapping the button simply removes the message. Optionally, tapping the text confirms the deletion and deletes the item immediately by calling the appropriate callback in your code. Don't forget to call back to your adapter's notifyItemRemoved()
:
public void onDismiss(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, int position) {
//TODO delete the actual item in your data source
adapter.notifyItemRemoved(position);
}