Search code examples
androidandroid-recyclerviewitemtouchhelper

How to know the direction in which recyclerview cell is being swiped?


To my recyclerview I have attached ItemTouchHelper. User can swipe in both direction i.e. left and right.

I would like to know is it possible to know as soon as user starts to drag a cell towards left or right and not after user have swiped the cell of recyclerview. Based on that I need to take some action on the cell.

I was going through the following method of ItemTouchHelper

@Override
    public int getDragDirs(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {

        return super.getDragDirs(recyclerView, viewHolder);
    }

but I don't know how to use it as the documentation is not proper.


Solution

  • You can check the direction of the swipe in onChildDraw() of ItemTouchHelper.Callback as soon as the view being swiped is selected and starts to move right or left:

    @Override
    public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
        if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) {
            // Here, if dX > 0 then swiping right. 
            // If dX < 0 then swiping left. 
            // If dX == 0 then at at start position.
        } else {
            super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
        }
    }