如何复制现有的 ListAdapter 列表,以便可以使用它来移动项目,然后通过将新复制的列表与原始列表进行比较来更新 UI?
也许Android开发人员在设计用于RecyclerView列表的ListAdapter的源代码时只想到了CRUD操作。如果是这样,他们就忽略了其他重要的 recyclerView 操作,例如过滤、排序和移动列表项。这些操作唯一改变的是排序顺序(排序和移动项目)或从原始列表中删除一些项目(用于过滤),但这现在需要 CustomAdapter?
我欣然接受将现有项目转换为 ListAdapter,因为我认为后台线程的更新对于稳定性和 UI 效率非常有价值。我的 CRUD 操作运行良好,但现在艰巨的任务是弄清楚如何进行其他过滤、排序和移动列表项。
我尝试移动 RecyclerView 列表中的项目,但拖放不起作用。以下是我迄今为止尝试过的不同方法的各种组合。与此同时,我阅读了 stackoverflow 上的所有其他 ListAdapter 问题...不幸的是我对 Kotlin 的了解为零,所以我正在寻找 Java 解决方案。我在这里缺少什么?
MainActivity 方法#1:
ItemTouchHelper.SimpleCallback itemTouchHelperCallback1 = new ItemTouchHelper.SimpleCallback(
(ItemTouchHelper.UP | ItemTouchHelper.DOWN),0) {
int dragFrom = -1;
int dragTo = -1;
@Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
int fromPos = viewHolder.getBindingAdapterPosition();
int toPos = target.getBindingAdapterPosition();
if (dragFrom == -1) {
dragFrom = fromPos;
}
dragTo = toPos;
cardsAdapter.moveItem(fromPos, toPos);
return true;
}
};
new ItemTouchHelper(itemTouchHelperCallback1).attachToRecyclerView(recyclerView);
MainActivity 方法#2,针对 onMove() 方法:
List newList = adapter.getCurrentList();
Quickcard quickcardItem = newList.get(fromPos);
newList.remove(fromPos);
newList.add(toPos, quickcardItem);
cardsAdapter.moveItem(fromPos, toPos);
cardsAdapter.notifyItemMoved(fromPos, toPos);
cardsAdapter.submitList(newList);
return true;
ListAdapter 方法#1:
public class CardsAdapter extends ListAdapter<Quickcard, CardsAdapter.ItemHolder> {
private final LayoutInflater layoutInflater;
protected CardsAdapter(@NonNull LayoutInflater layoutInflater, DiffUtil.ItemCallback<Quickcard> diffCallback) {
super(diffCallback);
this.layoutInflater = layoutInflater;
}
... // ViewHolder code
public void moveItem(int fromOldPos, int toNewPos) {
// Copy the ListAdapter's existing list
ArrayList<Quickcard> currList = new ArrayList<>(getCurrentList());
if (fromOldPos == toNewPos) {
return;
}
Collections.swap(currList, toNewPos, fromOldPos);
notifyItemMoved(fromOldPos, toNewPos);
submitList(currList);
}
}
ListAdapter 方法#2,用于 moveItem() 方法:
List<Quickcard> currList = getCurrentList();
List<Quickcard> copiedList = new ArrayList<>(currList);
if (fromOldPos == toNewPos) {
return;
}
if (fromOldPos < toNewPos) { // the q. is being moved down the q.list
for (int i = fromOldPos; i < toNewPos; i++) {
Collections.swap(copiedList, i,i + 1);
}
} else { // the q. is being moved up the q.list
for (int i = fromOldPos; i > toNewPos; i--) {
Collections.swap(copiedList, i,i - 1);
}
}
notifyItemMoved(fromOldPos, toNewPos);
submitList(copiedList);