I have used ItemTouchHelper
to implement drag and drop in recyclerview
. It works fine. But it is working only on long press. I need to do it with onTouch
ItemTouchHelper.Callback itemTouchHelperCallback = new ItemTouchHelper.Callback() {
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
Collections.swap(strings, viewHolder.getAdapterPosition(), target.getAdapterPosition());
adapter.notifyItemMoved(viewHolder.getAdapterPosition(), target.getAdapterPosition());
return true;
}
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
//TODO
}
//defines the enabled move directions in each state (idle, swiping, dragging).
@Override
public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
return makeFlag(ItemTouchHelper.ACTION_STATE_DRAG,
ItemTouchHelper.DOWN | ItemTouchHelper.UP | ItemTouchHelper.START | ItemTouchHelper.END);
}
};
This is the code I used. Please help me!!!
Override ItemTouchHelper
's isLongPressDragEnabled
and return false
https://developer.android.com/reference/android/support/v7/widget/helper/ItemTouchHelper.Callback#isLongPressDragEnabled()
override fun isLongPressDragEnabled(): Boolean = false
Add a callback to ViewHolder's implementation and use this
buttonToDrag.setOnTouchListener { v, event ->
listener.onTouch(this, event)
false
}
In the activity or fragment, use startDrag
private lateinit var itemTouchHelper: ItemTouchHelper
override fun onTouch(viewHolder: RecyclerView.ViewHolder, event: MotionEvent) {
if (event.actionMasked == MotionEvent.ACTION_DOWN) {
itemTouchHelper.startDrag(viewHolder)
}
}
I found the implementation in the doc of https://developer.android.com/reference/android/support/v7/widget/helper/ItemTouchHelper#startdrag
I've tried it personally and it works like a charm.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With