Disable Swipe for position in RecyclerView using ItemTouchHelper.SimpleCallback

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

    First in recyclerView at onCreateViewHolder method, set tag for each viewHolder type, like below code:

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        if(ITEM_TYPE_NORMAL == viewType) {
            View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.deposite_card_view, viewGroup, false);
            ItemViewHolder holder = new ItemViewHolder(context, v);
            holder.itemView.setTag("normal");
            return holder;
        } else {
            View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_header, viewGroup, false);
            HeaderViewHolder holder = new HeaderViewHolder(context, v);
            holder.itemView.setTag("header");
            return holder;
        }
    } 
    

    then in ItemTouchHelper.Callback implementation, update getMovementFlags method, like below:

    public class SwipeController extends ItemTouchHelper.Callback {
    
    @Override
    public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
        if("normal".equalsIgnoreCase((String) viewHolder.itemView.getTag())) {
            return makeMovementFlags(0, LEFT | RIGHT);
        } else {
            return 0;
        }
    }
    

    at end attach to recyclerView:

    final SwipeController swipeController = new SwipeController();
    
        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(swipeController);
        itemTouchHelper.attachToRecyclerView(recyclerView);
    

提交回复
热议问题