PrzemekTom
PrzemekTom

Reputation: 1994

RecyclerView ItemTouchHelper Action Drag Started

I've got RecyclerView with attached ItemTouchHelper, which I construct with

class ItemTouchHelperCallback(
        private val adapter: ItemTouchHelperAdapter
) : ItemTouchHelper.Callback() {
    override fun isLongPressDragEnabled(): Boolean {
        return true
    }
    ...
}

I am going to call vibration on every drag event start. In exact drag start moment.

To do it, inside ViewHolder I set touch listener. Then I tried to call vibration for the first ACTION_MOVE event. Unfortunately, it happens faster than item drag is possible. I want vibration and possibility to move items happen at the same time. To give user accurate haptic feedback, that he is able to drag and move items from now on.

I expected ItemTouchHelper or ItemTouchHelper.Callback to expose appropriate API. It doesn't. But I noticed that inside ItemTouchHelper there's mActionState with value ACTION_STATE_DRAG at the expected moment (inside onLongPress() So those 2 classes should know when drag starts! It's a pity they don't share their knowledge publicly.

Also, I've noticed very similar topic about action drag ended but I couldn't find solution to action drag started there.

Upvotes: 1

Views: 787

Answers (2)

vadiole
vadiole

Reputation: 387

You need to add this method to your callback

  override fun onSelectedChanged(viewHolder: ViewHolder?, actionState: Int) {
      super.onSelectedChanged(viewHolder, actionState)

        if (actionState == ACTION_STATE_DRAG) {
            //  your code here 
        }
  }

This works well for me

Upvotes: 2

PrzemekTom
PrzemekTom

Reputation: 1994

I found hacky solution in the end, which is part of ItemTouchHelper.Callback(). getMovementFlags is called in almost the same moment like change mActionState to ACTION_STATE_DRAG. Inside onLongPress() of ItemTouchHelper`.

Called twice, so watch out for that ;-)

Tested on compileSdkVersion = 28

I'd like to see better solution though.

Upvotes: 1

Related Questions