本文首发于公众号"AntDream",欢迎微信搜索"AntDream"或扫描文章底部二维码关注,和我一起每天进步一点点
要实现这个拖动重排序功能,主要是用到了RecycleView的ItemTouchHelper类
首先是定义一个接口
kotlin
interface ItemTouchHelperAdapter {
fun onItemMove(fromPosition: Int, toPosition: Int)
}
然后我们的Adapter里面要实现这个接口
kotlin
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接口方法
kotlin
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参数
如果是水平拖动,则用
kotlin
ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT
如果是竖直方向上拖动,则是用
kotlin
ItemTouchHelper.UP or ItemTouchHelper.DOWN
最后绑定到我们的RecycleView上
kotlin
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支持拖动重排序的功能
欢迎关注我的公众号AntDream查看更多精彩文章!