我实现了一个操作模式工具栏,它允许我删除 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/