How to clear highlighted items in the recyclerview?

后端 未结 2 1296
温柔的废话
温柔的废话 2020-12-04 03:25

I have implemented the recycler view multiple item selection by changing the background color of item when selected.When i remove those items from the model, items get remov

2条回答
  •  萌比男神i
    2020-12-04 04:05

    Try this:

    Take a Boolean variable in your POJO class

    public class POJO {
    
        boolean isSelected;
    
        public boolean isSelected() {
            return isSelected;
        }
    
        public void setSelected(boolean selected) {
            isSelected = selected;
        }
    }
    

    make below change in your onBindViewHolder() method

     @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
    
        if(pojoArrayList.get(position).isSelected()){
            // make selection in your item
        }else {
            //remove selction from you item
        }
    }
    

    Now inside your onLongClickListener make your selection true

    sample code

        sampleButton.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
    
                // set the status of selection 
                pojoArrayList.get(position).setSelected(true);
    
                return true;
            }
        });
    

    And when your want to remove selection use this

      pojoArrayList.get(position).setSelected(false);
    

    and when you want to delete item from list use that boolean variable to delete item

     if(pojoArrayList.get(position).isSelected()){
            //remove the item from list
           // and  notifyDataSetChanged(); after removing the item from list
     }
    

提交回复
热议问题