我想要实现的目标:拥有一个带有 GridLayoutManager 的 RecyclerView,它支持拖放,并在拖动时重新排列项目。
旁注:第一次使用拖放开发任何东西。
有很多关于如何使用 ListView 实现此功能的主题,例如:https ://raw.githubusercontent.com/btownrippleman/FurthestProgress/master/FurthestProgress/src/com/anappforthat/android/languagelineup/DynamicListView.java
然而,这些示例通常包含大量代码,用于创建拖动视图的位图,感觉应该可以使用View.startDrag(...)
RecyclerView来实现相同的结果notifyItemAdded()
,因为它们提供了重新排列动画。notifyItemMoved()
notifyItemRemoved()
所以我玩了一些并想出了这个:
final CardAdapter adapter = new CardAdapter(list);
adapter.setHasStableIds(true);
adapter.setListener(new CardAdapter.OnLongClickListener() {
@Override
public void onLongClick(View view) {
ClipData data = ClipData.newPlainText("","");
View.DragShadowBuilder builder = new View.DragShadowBuilder(view);
final int pos = mRecyclerView.getChildAdapterPosition(view);
final Goal item = list.remove(pos);
mRecyclerView.setOnDragListener(new View.OnDragListener() {
int prevPos = pos;
@Override
public boolean onDrag(View view, DragEvent dragEvent) {
final int action = dragEvent.getAction();
switch(action) {
case DragEvent.ACTION_DRAG_LOCATION:
View onTopOf = mRecyclerView.findChildViewUnder(dragEvent.getX(), dragEvent.getY());
int i = mRecyclerView.getChildAdapterPosition(onTopOf);
list.add(i, list.remove(prevPos));
adapter.notifyItemMoved(prevPos, i);
prevPos = i;
break;
case DragEvent.ACTION_DROP:
View underView = mRecyclerView.findChildViewUnder(dragEvent.getX(), dragEvent.getY());
int underPos = mRecyclerView.getChildAdapterPosition(underView);
list.add(underPos, item);
adapter.notifyItemInserted(underPos);
adapter.notifyDataSetChanged();
break;
}
return true;
}
});
view.startDrag(data, builder, view, 0);
}
});
mRecyclerView.setAdapter(adapter);
这段代码的工作,我得到了交换,但非常不稳定/不稳定,有时当它刷新时,整个网格被重新排列回原始顺序或随机的东西。无论如何,上面的代码只是我的第一次快速尝试,我真正更感兴趣的是是否有一些标准/最佳实践方法可以使用 ReyclerView 进行拖放,或者解决它的正确方法是否仍然相同多年来一直用于 ListViews?