Disable Swipe for position in RecyclerView using ItemTouchHelper.SimpleCallback

前端 未结 7 618
面向向阳花
面向向阳花 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:26

    There are a few ways to go about this, but if you only have one ViewHolder, but more than one layout you can take this approach.

    Override the getItemViewType and give it some logic as to determine view type based on position or type of data in object (I have a getType function in my object)

    @Override
    public int getItemViewType(int position) {
        return data.get(position).getType;
    }
    

    Return proper layout in onCreateView based on ViewType (Make sure to pass view type to ViewHolder class.

    @Override
    public AppListItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        mContext = parent.getContext();
    
        if (viewType == 0){
            return new AppListItemHolder(LayoutInflater.from(mContext).inflate(R.layout.layout, parent, false), viewType);
        else
            return new AppListItemHolder(LayoutInflater.from(mContext).inflate(R.layout.header, parent, false), viewType);
        }
    }
    

    Get the content views of the different layouts based on view type public static class AppListItemHolder extends RecyclerView.ViewHolder {

        public AppListItemHolder (View v, int viewType) {
            super(v);
    
            if (viewType == 0)
                ... get your views contents
            else
                ... get other views contents
            }
        }
    }
    

    And then in your ItemTouchHelper change actions based on ViewType. For me this disables swiping of a RecyclerView section header

    @Override
    public int getSwipeDirs(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
        if (viewHolder.getItemViewType() == 1) return 0;
            return super.getSwipeDirs(recyclerView, viewHolder);
        }
    }
    

提交回复
热议问题