0

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();
        }
    };
Diogo Simao
  • 85
  • 1
  • 1
  • 5
  • The ItemTouchHelper works only for fully swiping 1 item per time. In order to stop it in middle or as soon as there is a swipe - you need to [lock the swipe](https://stackoverflow.com/questions/33549637/how-can-recyclerview-itemtouchhelper-lock-swipe-item). Alternatively you can look in to [swipe with undo](https://www.tutorialsbuzz.com/2019/10/android-recyclerview-swipe-delete-undo-ItemTouchHelper-kotlin.html) or [swipe reveal layout](https://github.com/chthai64/SwipeRevealLayout) – Nitish Sep 29 '21 at 10:45
  • you can update recycleview on NO. – Syed Hamza Hassan Sep 29 '21 at 10:54
  • @Nitish reveal layout is conflicting with androidX – AtomicallyBeyond Dec 18 '21 at 23:36
  • @jamesfields , what kind of conflict? – Nitish Dec 20 '21 at 04:48

0 Answers0