我尝试在两个带有重新排序项目的RecyclerView之间实现拖放。 现在,我几乎完成了这项任务,但是遇到了一件困难的事情:当我将一个视图移到另一个视图时,它会多次从源到目标以及从目标到源多次移动。我想我需要等待动画完成或其他决定-我不知道该怎么做。
这是kotlin中View.OnDragListener的代码。 OnDragListener应用于两个RecyclerView
inner class DragListener : View.OnDragListener {
private var draggedWord: String? = null
private var draggedPosition = -1
override fun onDrag(v: View, event: DragEvent): Boolean {
val draggedView = event.localState as View? ?: return true
val target = v as RecyclerView
val targetAdapter = if (target.id == R.id.workWordsArea) workAdapter else inputAdapter
when (event.action) {
DragEvent.ACTION_DRAG_ENTERED -> {
if (draggedWord != null) {
return true
}
val layoutManager = target.layoutManager as GridLayoutManager
if (draggedView is TextView) {
val position = layoutManager.getPosition(draggedView)
draggedPosition = position
draggedWord = targetAdapter[position]
targetAdapter.setDummy(position)
targetAdapter.notifyItemChanged(position)
}
}
DragEvent.ACTION_DRAG_EXITED -> {
if (draggedPosition == -1) return true
targetAdapter.remove(draggedPosition)
targetAdapter.notifyItemRemoved(draggedPosition)
targetAdapter.notifyItemRangeChanged(draggedPosition, targetAdapter.size - draggedPosition)
draggedPosition = -1
}
DragEvent.ACTION_DRAG_LOCATION -> {
// drop to end always
if (target.id == R.id.inputWordsArea) {
return true
}
val layoutManager = target.layoutManager as GridLayoutManager
val targetView = target.findChildViewUnder(event.x, event.y)
if (targetView != null && targetView is TextView) {
val targetPosition = layoutManager.getPosition(targetView)
if (targetAdapter[targetPosition] == "d") {
return false
}
if (draggedPosition == -1) {
targetAdapter.insertDummy(targetPosition)
targetAdapter.notifyItemInserted(targetPosition)
draggedPosition = targetPosition
} else {
if (targetPosition != draggedPosition) {
targetAdapter.moveDummy(draggedPosition, targetPosition)
targetAdapter.notifyItemMoved(draggedPosition, targetPosition)
draggedPosition = targetPosition
}
}
}
}
DragEvent.ACTION_DROP -> {
// drop to end
if (draggedPosition == -1) {
targetAdapter.add(draggedWord!!)
targetAdapter.notifyItemInserted(targetAdapter.size - 1)
} else {
targetAdapter.set(draggedPosition, draggedWord!!)
targetAdapter.notifyItemChanged(draggedPosition)
}
// reset dragged vars
draggedWord = null
draggedPosition = -1
}
}
return true
}
}