CheckBox selection in RecyclerView is disorderly

onBindViewHolder中如下代码
holder.checkBox.setChecked(model.IsCheck);
//CheckBox事件监听
holder.checkBox.setOnCheckedChangeListener((buttonView, isChecked) -> model.IsCheck = isChecked);

It will cause confusion. I don’t feel like I’m talking about the point when I see many bloggers’ articles.

Because this model is obtained with the position returned by the method, but the item will be reused when sliding, the value of position is no longer accurate, and should be used

holder.getAdapterPosition()去获取最新的position。

The following log:

onCheckedChanged:  adapterPosition = 6
onCheckedChanged:  Position = 0
onCheckedChanged: isChecked = false

When sliding to Article 6, the entry is reused with Article 0, but the state of Article 6 is false. If the original position is still used, the state of Article 0 will be confused.

solution:

1. Use holder.getAdapterPosition() to retrieve the model value

            holder.checkBox.setChecked(model.IsCheck);
            //CheckBox事件监听
            holder.checkBox.setOnCheckedChangeListener((buttonView, isChecked)
                    -> mList.get(holder.getAdapterPosition()).IsCheck = isChecked);

2. Use setOnClickListener to set the monitor instead, and set the state again after clicking it.

           holder.checkBox.setChecked(model.IsCheck);
            //CheckBox事件监听
            holder.checkBox.setOnClickListener(v -> model.IsCheck = !model.IsCheck);

Comparatively speaking, the first method correctly uses the characteristics of RecyclerView and CheckBox; the second method avoids the influence of the CheckBox control on the value, and the value is only switched when clicked.

 

 

Guess you like

Origin blog.csdn.net/beita08/article/details/110080610