Search code examples
androidandroid-recyclerviewswipe

How to prevent swipe left or right on a RecyclerView in Android


I have created a simple RecyclerView and i am using the below Swipe Listener:

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

                @Override
                public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                    //do nothing, we only care about swiping
                    return false;
                }

                @Override
                public void onSwiped(RecyclerView.ViewHolder viewHolder, int swipeDir) {
                    if(swipeDir == ItemTouchHelper.RIGHT){
                        Toast.makeText(getContext(), "Swiped right", Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(getContext(), "Swiped left", Toast.LENGTH_SHORT).show();
                    }

                }
            }).attachToRecyclerView(recyclerView);

I want to allow only right swipe and prevent left swipe. So when the user tries to swipe left i want the item NOT to disappear.

How can i do that?


Solution

  • If you want to enable only some swipe/drag movements you need to override the method @Override public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) of ItemTouchHelper.Callback (superclass of ItemTouchHelper.SimpleCallback)

    For example if you want to enable only right swipe:

    @Override public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
        int dragFlags = 0;
        int swipeFlags = ItemTouchHelper.RIGHT;
    
        return makeMovementFlags(dragFlags, swipeFlags);
    }