How to clear highlighted items in the recyclerview?

后端 未结 2 1294
温柔的废话
温柔的废话 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条回答
  • 2020-12-04 03:45

    Your problem is in when (holder.is_selected.isChecked) {

    You should have the information if an item is checked on the ViewModel, not on the View and most definitely not in the ViewHolder.

    It should be something like if(residentItems.get(posistion).isSelected){ (Using when is overkill for binary cases)

    0 讨论(0)
  • 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
     }
    
    0 讨论(0)
提交回复
热议问题