在RecyclerView中将拖放拖放到特定位置

时间:2019-01-16 10:17:12

标签: android kotlin android-recyclerview drag-and-drop

是否有任何方法可以使用RecyclerView暂停项目的拖放到特定位置。 我已经使用下面的代码实现了拖放。

    val _ithCallback = object : ItemTouchHelper.Callback() {

    //and in your implementation of
    override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean {
        val fromPosition = viewHolder.adapterPosition
        val toPosition = target.adapterPosition

        // Video position
        if (fromPosition == list.size - 1 || toPosition == list.size - 1) {
            return false
        }

        if (list[fromPosition].trim().isEmpty()){
            return false
        }

        if (fromPosition < toPosition) {
            for (i in fromPosition until toPosition) {
                Collections.swap(list, i, i + 1)
            }
        } else {
            for (i in fromPosition downTo toPosition + 1) {
                Collections.swap(list, i, i - 1)
            }
        }
        adapter?.notifyItemMoved(fromPosition, toPosition)

        return true
    }

    override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {

    }

    //defines the enabled move directions in each state (idle, swiping, dragging).
    override fun getMovementFlags(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder): Int {
        return makeFlag(ItemTouchHelper.ACTION_STATE_DRAG,
                ItemTouchHelper.DOWN or ItemTouchHelper.UP or ItemTouchHelper.START or ItemTouchHelper.END)
    }
}

并像这样使用它

val ith = ItemTouchHelper(_ithCallback)
ith.attachToRecyclerView(imagesRecyclerView)

1 个答案:

答案 0 :(得分:0)

最后,在 ItemTouchHelper 类中进行了大量研究之后,我像这样解决了它。

我所做的是将标志设置为ACTION_STATE_IDLE,我要在其中停止拖放。希望它能帮助像我这样的人。

以下是Kotlin版本。如果有人在JAVA中需要相同的东西,我可以将其转换。

//defines the enabled move directions in each state (idle, swiping, dragging).
    override fun getMovementFlags(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder): Int {
        // The position i want to lock/halt
        if (list[viewHolder.adapterPosition].trim().isEmpty()){
            return makeFlag(ItemTouchHelper.ACTION_STATE_IDLE, ItemTouchHelper.DOWN or ItemTouchHelper.UP)
        }
        // The position i want to lock/halt
        if (viewHolder.adapterPosition == list.size - 1){
            return makeFlag(ItemTouchHelper.ACTION_STATE_IDLE, ItemTouchHelper.DOWN or ItemTouchHelper.UP)
        }
        // else enabling ACTION_STATE_DRAG
        return makeFlag(ItemTouchHelper.ACTION_STATE_DRAG,
                ItemTouchHelper.DOWN or ItemTouchHelper.UP or ItemTouchHelper.START or ItemTouchHelper.END)
    }