I have this code and my goal was to delete an item from the recycler view with a swipe both to the left and to the right, but before this item is deleted I wanted an alert dialog to be shown for the user to confirm if he really wants to delete the item from the recycler view.
In this code, when the swipe is done, the item is removed from the recycler view and only then shows the alert dialog.
ItemTouchHelper.SimpleCallback callback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
@Override
public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
return false;
}
@Override
public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
AlertDialog.Builder builder = new AlertDialog.Builder(SensorActivity.this);
builder.setMessage("Do you want cancel?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(SensorActivity.this, "Data Deleted",Toast.LENGTH_LONG).show();
sensorModels.remove(viewHolder.getAdapterPosition());
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
builder.show();
sensorAdapter.notifyDataSetChanged();
}
};