简体   繁体   中英

Android - Recycler view set item not swipeable

I am using a RecyclerView and ItemTouchHelper.SimpleCallback => onSwiped method. Some of the items at the recycler view are in progress and i want to disable swipe on them.

How can i do it?

You can override getSwipeDirs() in your ItemTouchHelper.SimpleCallback . Return 0 when you don't want an item to be swipe-able.

The second parameter to this method is the ViewHolder for the item being swiped- you can add a simple flag to your ViewHolder to indicate whether or not it is swipe-able.

For example:

static class SwipeViewHolder extends RecyclerView.ViewHolder {
    public boolean isSwipeable;

    public SwipeViewHolder(View itemView) {
        super(itemView);
    }
}

And the callback:

static class DragAndSwipeCallback extends ItemTouchHelper.SimpleCallback {

    public DragAndSwipeCallback(int dragDirs, int swipeDirs) {
        super(dragDirs, swipeDirs);
    }

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

    @Override
    public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
        // Remove item
    }

    @Override
    public int getSwipeDirs(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
        if (viewHolder instanceof SwipeViewHolder
                && ((SwipeViewHolder) viewHolder).isSwipeable) {
            return super.getSwipeDirs(recyclerView, viewHolder);
        } else {
            return 0;
        }
    }
}

In my case I noticed getSwipeDirs() wasn't being called, probably because I had set movementFlags as well.

I had to override getMovementFlags() as well, like so:

        @Override
        public int getMovementFlags(RecyclerView recyclerView,
                                    RecyclerView.ViewHolder viewHolder) {
            if (viewHolder instanceof SwipeViewHolder
                    && ((SwipeViewHolder) viewHolder).isSwipeable) {
                return makeMovementFlags(0, super.getSwipeDirs(recyclerView, viewHolder));
            } else {
                return makeMovementFlags(0, 0);
            }
        }

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