【问题标题】:Remove multiple selected items from a RecyclerView从 RecyclerView 中删除多个选定项目
【发布时间】:2020-06-05 19:33:17
【问题描述】:

我实现了一个操作模式工具栏,允许我删除我的 recyclerView 中的多个项目。我有一个所有选定项目索引的整数列表。所以我想知道执行我的请求的更好方法是什么。

目前,当我尝试删除 3 个项目时,出现错误:java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionNoteListViewHolder


这是我的代码:

     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();
    }

【问题讨论】:

    标签: java android android-studio android-recyclerview android-actionmode


    【解决方案1】:

    这里的选项很少,您可以将代码更改为,而不是调用removeAll,然后像添加项目和使用notifyItemInserted 时那样直接调用notifyItemRemoved 来删除。

    您也可以通过一次调用 notifyDataSetChanged 将您的 for 循环替换为 notifyItemRemoved,但这不是最佳解决方案。为了获得更好的性能,您应该考虑使用DiffUtil

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-24
    • 2021-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多