Checking a checkbox in listview makes other random checkboxes checked too

后端 未结 3 1325
耶瑟儿~
耶瑟儿~ 2020-11-28 09:14

whenever i check a checkbox in my listview , other random checkboxes get checked too . It could be due to item recycling by listview.

I also tried setting android:f

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-28 10:00

    You need to keep track of the check state, because ListView re-uses the Views. so the state for position one which was previously enabled/disabled may appear as is for position 7.

    So what you need to do is keep the checked state in an array boolean or whatever you prefer.

    Take a class level boolean [] checkedState; initialize it in constructor, according to your data array size, you can use ArrayList too for dynamic size.

    set OnStateChangeListener to your CheckBoxes in getView(), whenever it is checked or un-checked, take the position and save it in the array of checkedState like this:

    checkedState[position] = false;// or true accordingly
    

    and when setting other data for View like TextView or ImageView for any specific position, set the checked state also accordingly like this:

    holder.appIcon.setImageDrawable(appInfoList.get(position).loadIcon(pm));
    holder.ckbox.setChecked(checkedState[position]);
    

    A very good explanation and example:

    Android custom image gallery with checkbox in grid to select multiple

    Edit: Actually what is happening is, you position is getting buggy, to solve this add these lines:

    holder.ckbox.setText(appInfoList.get(position).loadLabel(pm));
    holder.ckbox.setTag(String.valueOf(position));   // to properly track the actual position
    holder.ckbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
          @Override
          public void onCheckedChanged(CompoundButton v, boolean isChecked) {
                int pos = Integer.parseInt( v.getTag().toString()) ; //to take the actual position
                positionArray.add(pos, isChecked);  // we don't need to check whether it is true or false, however you can put if-else to debug the app.
    
          }
    });
    

提交回复
热议问题