【发布时间】:2019-07-05 17:35:36
【问题描述】:
我有一个简单的待办事项列表应用程序,其中包含一个 RecyclerView/FirestoreRecyclerAdapter/ItemTouchHelper,其中包含项目 A、B、C、D(见附图)。现在我想将这些项目的位置有效地存储在 Firestore 中,最初是在我添加项目时以及垂直拖放它们时。我如何在概念上或使用现有/示例代码来做到这一点。将它存储在云中很重要,这样如果我从另一台设备上查看它,项目的位置就会保持不变。
关于它的一些想法: 适配器位置 (int) 从 0 开始(在本例中为 D)。当我添加项目 E 时,它的适配器位置为 0,并且所有其他项目的位置都发生了变化。因此,每次添加新项目时,Firestore 中的存储位置可能会增加 1,该项目将显示在顶部。但是,如果我有成千上万的项目(例如在照片库应用程序中)怎么办。每次拖拽物品时更新所有物品的位置是否有效?
我想这应该是一个非常普遍的问题。
我的 Todo 应用程序的 MainActivity (https://i.stack.imgur.com/o3jJ1.jpg)
这是我的 ItemTouchHelper.Callback onMoved() 方法的代码:
@Override
public void onMoved(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, int fromPos, @NonNull RecyclerView.ViewHolder target, int toPos, int x, int y) {
super.onMoved(recyclerView, viewHolder, fromPos, target, toPos, x, y);
for (int maxItems = recyclerView.getChildCount(), i = 0; i < maxItems; ++i) {
RecyclerView.ViewHolder holder = recyclerView.getChildViewHolder(recyclerView.getChildAt(i));
int layoutPosition = holder.getLayoutPosition();
int adapterPosition = holder.getAdapterPosition();
TodoAdapter.TodoHolder h = (TodoAdapter.TodoHolder)holder;
String documentID = h.getDocumentID();
TextView textViewTitle = (TextView)h.itemView.findViewById(R.id.todo_title);
CharSequence title = textViewTitle.getText();
DocumentReference docRef = mFirestore.collection("todos").document(documentID);
docRef.update("position", adapterPosition);
}
}
【问题讨论】:
标签: android-recyclerview google-cloud-firestore position items