recyclerview 拖拽排序
public class ItemDragCallback extends ItemTouchHelper.Callback { private BleListAdapter mAdapter; private boolean mEdit; public ItemDragCallback(BleListAdapter mAdapter) { this.mAdapter = mAdapter; } // 该方法返回一个Flags表示Item的三种状态状态:idle(空闲)、 swiping(滑动)、dragging(拖动), @Override public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) { BleListAdapter adapter = (BleListAdapter) recyclerView.getAdapter(); mEdit = adapter.isEdit; //是否是编辑状态 if (!mEdit) { return 0; } //拖动支持 int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN|ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT; //滑动支持 int swipeFlags = 0/**ItemTouchHelper.START | ItemTouchHelper.END**/; return makeMovementFlags(dragFlags, swipeFlags); } // 当ItemTouchHelper拖动一个Item时该方法将会被回调,Item将从旧的位置移动到新的位置,如果不拖动这个方法将从来不会调用, @Override public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) { int fromPosition = viewHolder.getAdapterPosition(); //拖动的position int toPosition = target.getAdapterPosition(); //释放的position //适配器的方法 mAdapter.itemMove(fromPosition, toPosition); return true; } //当Item滑动的时候调用,如果不滑动该方法不会被调用,可通过direction做相应的判断执行某些操作。 @Override public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) { } //自定义您的视图如何响应用户交互,如果你不自定义拖动的话这个方法万万不能重写,不然会没动静。实践于(implementation 'com.android.support:recyclerview-v7:28.0.0') // @Override // public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) { // 自定义侧滑菜单 // } //自定义您的视图如何响应用户交互 @Override public void onChildDrawOver(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) { super.onChildDrawOver(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive); if (dX != 0 && dY != 0 || isCurrentlyActive) { BleListAdapter adapter = (BleListAdapter) recyclerView.getAdapter(); mEdit = adapter.isEdit; } } @Override public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) { super.clearView(recyclerView, viewHolder); //松手时调用 int position = viewHolder.getLayoutPosition(); Log.d("TAG", "clearView: "+"position"+position); } }
public class BleListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { public boolean isEdit = true;//是否是编辑状态 ...... /** * 对拖拽的元素进行排序 * @param fromPosition * @param toPosition */ void itemMove(int fromPosition, int toPosition) { if (fromPosition < toPosition) { for (int i = fromPosition; i < toPosition; i++) { Collections.swap(mSortedList, i, i + 1); } } else { for (int i = fromPosition; i > toPosition; i--) { Collections.swap(mSortedList, i, i - 1); } } notifyItemMoved(fromPosition, toPosition); } ...... }
使用
ItemDragCallback callback = new ItemDragCallback(bleListAdapter); ItemTouchHelper helper = new ItemTouchHelper(callback); helper.attachToRecyclerView(rv);