Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: RecyclerView item with LongClickListener and and drag and drop

So, I'm trying to figure this out. I see many posts online about having RecyclerView items with both swipe and drag-- I've got that down. But what I can't get to work is both drag and long press actions.

I've got working code for both drag and longclick, the problem is, when I long click a recycler item, it's a toss up whether it will run the longclick function or the drag function.

Here is the code for the long click listener:

        holder.itemView.setOnLongClickListener {
             currentNote.toggleSelection(it)
             // change the MainActivity menu to the selection menu
             MainActivity.currentMenu = R.menu.menu_select
             (it.context as Activity).invalidateOptionsMenu()

             // set a flag to change the onClickListener to select notes rather than edit/view
             SELECTING = true
             notifyDataSetChanged()

             true  

Simple enough. And here is how I implemented the drag action:

        val itemTouchHelper = ItemTouchHelper(object : ItemTouchHelper.Callback() {
        override fun isLongPressDragEnabled() = true
        override fun isItemViewSwipeEnabled() = true

        override fun getMovementFlags(
            recyclerView: RecyclerView,
            viewHolder: RecyclerView.ViewHolder
        ): Int {
            val dragFlags = UP or DOWN or START or END
            val swipeFlags = LEFT or RIGHT
            return makeMovementFlags(dragFlags, swipeFlags)
        }

        override fun onMove(
            recyclerView: RecyclerView,
            viewHolder: RecyclerView.ViewHolder,
            target: RecyclerView.ViewHolder
        ): Boolean {
            val fromPosition = viewHolder.adapterPosition
            val toPosition = target.adapterPosition
            val item = NOTES_ARRAY.removeAt(fromPosition)
            NOTES_ARRAY.add(toPosition, item)
            recyclerView.adapter!!.notifyItemMoved(fromPosition, toPosition)
            return true
        }
    })

This is a note taking app, so I use the long press action for doing multi select. So the question is, how can I differentiate between a long press action and a drag action, as they are both bound the the "long press."

I know that this is the problem, because if I comment out the onLongClickListener, I can easily drag and drop without issue.

like image 266
claxtastic Avatar asked Dec 31 '25 03:12

claxtastic


1 Answers

I think the recommended way to resolve this problem is to override ItemTouchHelper.Callback.isLongPressDragEnabled to return false and then call ItemTouchHelper.startDrag() in your long-click handler

like image 135
tipa Avatar answered Jan 01 '26 20:01

tipa