简体   繁体   中英

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?

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM