0

I've implemented a Custom list view with extending an ArrayAdapter class, The problem I was having that whenever I scrolled listview the checkbox items got unchecked , So I implemented the following code:

CheckBox cb = (CheckBox) myview.findViewById(R.id.grocery_item_checkbox);

            //Code to keep the status of checkbox checked, when scrolling up or down
            cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

                    if(!compoundButton.isChecked()){
                        checkbox_status[pos] = false;
                        Log.d("LOG", "Checkbox at position" + pos + "is set to" + checkbox_status[pos]);
                    }else{
                        checkbox_status[pos] = true;
                        Log.d("LOG", "Checkbox at position" + pos + "is set to" + checkbox_status[pos]);
                    }
                    notifyDataSetChanged();
                }
            });


            if(!checkbox_status[pos]){
                cb.setChecked(false);
            }else{
                cb.setChecked(true);
            }

Here checkbox_status is a boolean array to store the status of checkbox. and posrefers to the position in getView method.

The Problem I'm having is whenever I click the top item in my listview the bottom item get checked:

say I click on item at position 0 but item at position 6 get checked.

And the status of checkboxes also disturbs again when I scroll up or down.

yousafkh
  • 94
  • 1
  • 7

1 Answers1

0

First, you are setting a listener and then, you are setting checked\unchecked. It triggers the listener.

After that, I do not know if you are using viewholder pattern. If you don't, you need to use it. Otherwise your problem will continue.

In getView method on your adapter, you should implement like below:

//in some cases, it will prevent unwanted situations
cb.setOnCheckedChangeListener(null);


if(!checkbox_status[pos]){
    cb.setChecked(false);
}else{
    cb.setChecked(true);
}

//Code to keep the status of checkbox checked, when scrolling up or down
cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
      @Override
      public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

           if(!compoundButton.isChecked()){
               checkbox_status[pos] = false;
               Log.d("LOG", "Checkbox at position" + pos + "is set to" + checkbox_status[pos]);
           }else{
               checkbox_status[pos] = true;
               Log.d("LOG", "Checkbox at position" + pos + "is set to" + checkbox_status[pos]);
           }
           notifyDataSetChanged();
       }
});
Oğuzhan Döngül
  • 7,856
  • 4
  • 38
  • 52