简体   繁体   中英

Remove multiple selected items from a RecyclerView

I implemented an action mode toolbar that allows me to delete multiple items in my recyclerView. I have a list of integer of all selected item index. So I would like to know what is the better way to perform my request.

Currently, when I try to remove 3 items, I have an error: java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionNoteListViewHolder java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionNoteListViewHolder


This is my code:

     private void deleteNote() {
        List<Note> temp = new ArrayList<>(notes);
        List<Integer> selectedItems = noteListAdapter.getSelectedItems();

        notes.removeAll(selectedItems.stream().map(notes::get).collect(Collectors.toList()));
        for (int notes_index: selectedItems) {
            noteListAdapter.notifyItemRemoved(notes_index);
        }

        Snackbar snackbar = Snackbar.make("test").setAction("ANNULER", v1 -> {
            // reinsert the note if undo action
            for (int index: selectedItems) {
                notes.add(index, temp.get(index));
                noteListAdapter.notifyItemInserted(index);
            }
        });

        snackbar.show();
    }

Few options here, you could change your code to instead of calling removeAll , to remove one by one calling notifyItemRemoved straight afterwards like you did when adding items and using notifyItemInserted .

You could also replace your for loop with notifyItemRemoved by a single call to notifyDataSetChanged but it's not an optimal solution. For better performance, you should look on using DiffUtil .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM