实现RecyclerView拖动排序和滑动删除,我想到的是 ViewDragHelper ,或者是第三方库,当我看了 ToDoList 的时候,发现原来官方已经支持RecyclerView拖动排序与滑动删除,那就是ItemTouchHelper。
简介
“ItemTouchHelper is a utility class to add swipe to dismiss and drag & drop support to RecyclerView.
It works with a RecyclerView and a Callback class, which configures what type of interactions are enabled and also receives events when user performs these actions.
Depending on which functionality you support, you should override onMove(RecyclerView, ViewHolder, ViewHolder) and / or onSwiped(ViewHolder, int).”
ItemTouchHelper 实现RecyclerView拖动排序和滑动删除,我们需要重写方法:
指定可以支持的拖放和滑动的方向,上下为拖动(drag),左右为滑动(swipe)
|
|
滑动操作
|
|
删掉操作
实践
依赖
app/build.gradle
效果预览
线性
网格
ItemTouchHelperCallback
新建ItemTouchHelperCallback继承ItemTouchHelper.Callback,完整代码如下:
attachToRecyclerView
创建ItemTouchHelper对象,然后调用attachToRecyclerView(RecyclerView) 方法
源码
更多详见源码:https://github.com/WuXiaolong/AndroidSamples/ ,很多参考了iPaulPro/Android-ItemTouchHelper-Demo,关键需要消化,转化成自己的东西。
参考
官网Api
Drag and Swipe with RecyclerView
Drag and Swipe with RecyclerView—Part Two