如何在列表视图中实现拖放? [英] How to implement Drag&Drop in listview?
问题描述
我发现大多数类似的问题是几年前提出的.因此,我想知道是否存在一种新的,更简单的方法来实现对列表视图的拖放功能?我正在从sqilte db获取我的listview对象的数据.我没有找到一些简单的教程.如果有,请共享链接.
I have found that most of the similar questions were asked years ago. Therefore, I would like to know if there are a new and easier ways to implement drag&drop functionality to listview? I'm taking the data from sqilte db for my listview object. I didn't find some straightforward tutorial. If there is please share the link.
我找到了以下视频: https://www.youtube.com/watch?v = _BZIvjMgH-Q 但是代码链接无效.
I found this video: https://www.youtube.com/watch?v=_BZIvjMgH-Q but the link for code is not working.
推荐答案
如注释中所述,使用RecyclerView实现拖放的最简单方法.它包括名为ItemTouchHelper
的特殊类,可以轻松处理拖放功能.如果使用ListView,则与RecyclerView相比,您需要编写更多代码.
As it was told in the comments the easiest way to implement Drag&Drop by using RecyclerView. It includes the special class named ItemTouchHelper
which can easy handle the drag&drop feature. In case of ListView you will need to write a lot more code compared to RecyclerView.
以下代码是我发现有用的代码:
The following code is what I have found useful:
ItemTouchHelper item = new ItemTouchHelper(new ItemTouchHelper.Callback() {
@Override
public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
int swipeFlags = 0;
return makeMovementFlags(dragFlags, swipeFlags);
}
@Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
Collections.swap(dateList, viewHolder.getAdapterPosition(), target.getAdapterPosition());
adapter.notifyItemMoved(viewHolder.getAdapterPosition(), target.getAdapterPosition());
return true;
}
@Override
public void onMoved(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, int fromPos, RecyclerView.ViewHolder target, int toPos, int x, int y) {
super.onMoved(recyclerView, viewHolder, fromPos, target, toPos, x, y);
Toast.makeText(MainActivity.this, "Moved", Toast.LENGTH_SHORT).show();
}
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {}
});
item.attachToRecyclerView(recyclerView);
这篇关于如何在列表视图中实现拖放?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!