Disable Swipe for position in RecyclerView using ItemTouchHelper.SimpleCallback

前端 未结 7 700
面向向阳花
面向向阳花 2021-01-30 02:44

I am using recyclerview 22.2.0 and the helper class ItemTouchHelper.SimpleCallback to enable swipe-to-dismiss option to my list. But as I have a type of header on it, I

7条回答
  •  不要未来只要你来
    2021-01-30 03:19

    Here's a simple way to do this that only depends upon the position of the item being swiped:

    @Override
    public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder holder) {
        int position = holder.getAdapterPosition();
        int dragFlags = 0; // whatever your dragFlags need to be
        int swipeFlags = createSwipeFlags(position)
    
        return makeMovementFlags(dragFlags, swipeFlags);
    }
    
    private int createSwipeFlags(int position) {
      return position == 0 ? 0 : ItemTouchHelper.START | ItemTouchHelper.END;
    }
    

    This should also work if you're using SimpleCallback:

    @Override
    public int getSwipeDirs(RecyclerView recyclerView, RecyclerView.ViewHolder holder) {
        int position = holder.getAdapterPosition();
        return createSwipeFlags(position);
    }
    
    private int createSwipeFlags(int position) {
      return position == 0 ? 0 : super.getSwipeDirs(recyclerView, viewHolder);
    }
    

    If you want to disable swiping conditional upon the data in the item, use the position value to get data from the adapter for the item being swiped and disable accordingly.

    If you already have specific holder types which need to not swipe, the accepted answer will work. However, creating holder types as a proxy for position is a kludge and should be avoided.

提交回复
热议问题