Android: ListView CheckBox checked unintentionally

2019-09-15 02:42发布

问题:

I have a ListView which is layout below a header bar and layout above a footer bar. Each row of the ListView contains a LinearLayout with a CheckBox and TextView side by side. Now, when I have more rows that can be shown at a time, you can of course scroll down or up. However, once I scroll down or up the first and / or last CheckBox is being checked automatically. My finger is nowhere near where you would select the check box. What could be causing this? Note I used code here: http://www.anddev.org/checkbox_text_list___extension_of_iconified_text_tutorial-t771.html

回答1:

Looking briefly into code presented under link in question I can see the following:

 public View getView(int position, View convertView, ViewGroup parent){
      CheckBoxifiedTextView btv;
      if (convertView == null) {
           btv = new CheckBoxifiedTextView(mContext, mItems.get(position));
      } else { // Reuse/Overwrite the View passed
           // We are assuming(!) that it is castable!
           CheckBoxifiedText src = mItems.get(position);
           btv = (CheckBoxifiedTextView) convertView;
           btv.setCheckBoxState(src.getChecked());  // set checked state
           btv = (CheckBoxifiedTextView) convertView;
           btv.setText(mItems.get(position).getText());
      }
      return btv;
 }

As you can see the view is reused during scroll and checkbox state is set with method setCheckBoxState. Then in CheckBoxifiedTextView you can find:

 public void setCheckBoxState(boolean bool)
 {
     mCheckBox.setChecked(mCheckBoxText.getChecked());
     mCheckBoxText.setChecked(true); // <-- HERE !
 } 

where in 4th line there is setChecked(true) hardcoded which might be causing the issue.