java - 从 RecyclerView 中删除多个选定的项目

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

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

目前,当我尝试删除 3 个项目时,出现错误:java.lang.IndexOutOfBoundsException:检测到不一致。 View 持有者适配器位置无效NoteListViewHolder

<小时/>

这是我的代码:

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

最佳答案

这里的选项很少,您可以更改代码,而不是调用 removeAll,而是直接调用 notifyItemRemoved 来逐一删除,就像添加项目和使用 notifyItemInserted

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

关于java - 从 RecyclerView 中删除多个选定的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62214142/

相关文章:

java - 如何在 java 中启动并与控制台应用程序交互

java - 在 url 中插入双引号时,索引处的查询中存在非法字符

Java - 套接字编程/阻塞端口

android - 如何使用 Malloc Debug 检查 native 内存泄漏?

java - 如何从 android studio 中删除不兼容类型错误

android - 应用程序未在 Genymotion 中启动

java - 为什么在框架构建后我的代码不被读取?

android - Gradle - Windows 中缓存库的位置

android-studio - 模拟器 : handleCpuAcceleration: feature check for hvf AND Emulator: added library vulkan-1. dll

android-studio - 为什么我的 native 库没有加载?