Drag Drop halt for Specific Position in RecyclerVi

2020-04-20 14:24发布

问题:

Is there any way to Halt the Drag Drop of item for specific position using RecyclerView. I have achieved the Drag & Drop using below code.

    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)
    }
}

and using it like this

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

回答1:

Finally, after lots of research in ItemTouchHelper class i resolved it like this.

What i have done is set the flag as ACTION_STATE_IDLE where i want to halt the Drag and Drop. Hope it helps someone like me.

Below is the Kotlin version. If anyone needs the same in JAVA i can convert it.

//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)
    }