要实现这个拖动重排序功能,主要是用到了RecycleView的ItemTouchHelper类
首先是定义一个接口
代码语言:javascript复制interface ItemTouchHelperAdapter {
fun onItemMove(fromPosition: Int, toPosition: Int)
}
然后我们的Adapter里面要实现这个接口
代码语言:javascript复制import androidx.recyclerview.widget.RecyclerView
import java.util.*
class MyAdapter(private val items: MutableList<String>) : RecyclerView.Adapter<MyAdapter.ViewHolder>(), ItemTouchHelperAdapter {
// ... ViewHolder and other methods ...
override fun onItemMove(fromPosition: Int, toPosition: Int) {
if (fromPosition < toPosition) {
for (i in fromPosition until toPosition) {
Collections.swap(items, i, i 1)
}
} else {
for (i in fromPosition downTo toPosition 1) {
Collections.swap(items, i, i - 1)
}
}
notifyItemMoved(fromPosition, toPosition)
}
}
实现ItemTouchHelper的Callback接口方法
代码语言:javascript复制class SimpleItemTouchHelperCallback(private val adapter: ItemTouchHelperAdapter) : ItemTouchHelper.Callback() {
override fun isLongPressDragEnabled() = true
override fun isItemViewSwipeEnabled() = false
override fun getMovementFlags(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder): Int {
//这里是水平拖动
val dragFlags = ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT
return makeMovementFlags(dragFlags, 0)
}
override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean {
adapter.onItemMove(viewHolder.adapterPosition, target.adapterPosition)
return true
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
// do nothing
}
}
其中控制拖动方向的主要是在getMovementFlags方法中的dragFlags参数
如果是水平拖动,则用
代码语言:javascript复制ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT
如果是竖直方向上拖动,则是用
代码语言:javascript复制ItemTouchHelper.UP or ItemTouchHelper.DOWN
最后绑定到我们的RecycleView上
代码语言:javascript复制val adapter = MyAdapter(myDataset)
val recyclerView = findViewById<RecyclerView>(R.id.my_recycler_view)
recyclerView.adapter = adapter
val callback = SimpleItemTouchHelperCallback(adapter)
val touchHelper = ItemTouchHelper(callback)
touchHelper.attachToRecyclerView(recyclerView)
完成以上的步骤就瞬间实现了让RecycleView支持拖动重排序的功能。
赶快动手试试吧!
作者介绍
中年程序猿,十年移动端开发老司机,分享一线开发经验和知识,正在探索通过副业渡过中年危机
越努力越幸运,加油