checkboxes gets unchecked in recyclerView upon scrolling

前端 未结 2 1106
别跟我提以往
别跟我提以往 2020-12-21 14:02

I have a cursor which retrieves a list of ingredients and populates an adapter, which is then assigned to a recycler View having checkboxes. The problem I\'ve got is that, w

相关标签:
2条回答
  • 2020-12-21 14:43

    use logic below on onBindView:

    holder.attenCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                    if (holder.attenCheckBox.isChecked())
                        dataModel.setChecked(true);
                    else
                        dataModel.setChecked(false);
                }
            });
    
            if (dataModel.getChecked())
                holder.attenCheckBox.setChecked(true);
            else
                holder.attenCheckBox.setChecked(false);
            holder.checkboxLinearLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (holder.attenCheckBox.isChecked())
                        holder.attenCheckBox.setChecked(false);
                    else
                        holder.attenCheckBox.setChecked(true);
                }
            });
    

    Explanation:

    • Recycle view inflate eveytime when you scroll down or up.
    • you need to store a flag in the data pojo to keep track of check status
    • using that flag with setOnCheckedChangeListener will enable you to have you checked enable/disable. Make sure you put flag after listener.
    0 讨论(0)
  • 2020-12-21 14:56

    RecyclerView removes (recycles) the unseen views from the layout on scrolling, this is the basic behavior of recyclerView in order to reduce memory use.

    When a view with a checkbox is recycled, a checked checkbox gets unchecked and if it has a listener, the listener gets called.

    You can remove the listener from the view when it is recycled. Just override the onViewRecycled method.

        @Override
        public void onViewRecycled(@NonNull MyViewHolder holder) {
            holder.checkBox.setOnCheckedChangeListener(null);
            super.onViewRecycled(holder);
        }
    

    When the view is constructed again, while scrolling, your listener will also be added again.

    0 讨论(0)
提交回复
热议问题