ItemTouchHelper get swipe directions

Viewed 3479

I need to change the background color of the row item based on the direction of swipe, if swiped right then change the color to Green, if swiped left then change the color to Red.

but I'm finding it difficult to get the direction of swipe.

here is my code.

public class SimpleItemTouchHelperCallback extends ItemTouchHelper.Callback 
{

private final ItemTouchHelperAdapter mAdapter;
public SimpleItemTouchHelperCallback(ItemTouchHelperAdapter mAdapter) {
    this.mAdapter = mAdapter;
}

@Override
public boolean isItemViewSwipeEnabled() {
    return true;
}

@Override
public boolean isLongPressDragEnabled() {
    return false;
}

@Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
    return false;
}

@Override
public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
    final int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
    final int swipeFlags = ItemTouchHelper.START |  ItemTouchHelper.END;
    return makeMovementFlags(dragFlags,swipeFlags);
}

@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
    if(direction == ItemTouchHelper.LEFT){
        Log.i("Swipe direction : ","Left");
    }
    else if (direction == ItemTouchHelper.RIGHT){
        Log.i("Swipe direction : ","Right");
    }
    mAdapter.onItemDismiss(viewHolder.getAdapterPosition());
}
}

I'm not getting any value in the logs.

Please suggest.

1 Answers

As, shown by Ramees, you can use the onChildDraw callback of ItemTouchHelper.SimpleCallback to detect the direction of the swipe while the swipe is being done, then you can use this callback to show a different item background based on the direction of the swipe. The onSwiped callback will detect the direction of the swipe once it is finished, there you can decide what action to take.

new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {

    @Override
    public void onChildDraw(@NonNull Canvas c, @NonNull RecyclerView recyclerView,
                            @NonNull RecyclerView.ViewHolder viewHolder, float dX, float dY,
                            int actionState, boolean isCurrentlyActive) {

        // dX (float) is the amount of horizontal displacement caused by user's action.            
        // If the horizontal displacement is positive the item is being 
        // swiped to the RIGHT, if it is negative the item is being 
        // swiped to the LEFT.

        if(dX >0) {
            // RIGHT swipe   
            } else {
            // LEFT swipe
            }
    }

}).attachToRecyclerView(mRecyclerView);
Related