mercredi 24 juin 2015

Android - ListView with CheckBoxes get unchecked even when saving states

It's been 2 days and I'm beginning to lose hope in my programming abilities.
Here's my BaseAdapter :

private Context ctx;
private ArrayList<MultiSelectionItem> items;
private LayoutInflater layoutInflater;
private boolean[] checked;

// Constructor
public MultiSelectionSpinnerAdapter(Context ctx, ArrayList<MultiSelectionItem> items) {
    this.ctx = ctx;
    this.items = items;
    this.layoutInflater = LayoutInflater.from(ctx);

    checked = new boolean[items.size()];
    for (int i = 0; i < checked.length; i++) {
        checked[i] = true; // Notice I'm setting all checkboxes to checked !
    }
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    final MultiSelectionItem item = items.get(position);

    CheckBox checkBox = (CheckBox) convertView;
    if (checkBox == null) {
        checkBox = (CheckBox) layoutInflater.inflate(R.layout.multi_selection_checkbox, parent, false);
    }

    checkBox.setText(item.getLabel());
    checkBox.setTag(Integer.valueOf(position));
    checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            // isChecked is always false !!!!
            checked[(Integer) buttonView.getTag()] = isChecked;
        }
    });
    checkBox.setChecked(checked[position]);

    return checkBox;
}

CheckBoxes states get stored correctly in checked array, HOWEVER...
Even though I do checkBox.setChecked(true), isChecked parameter in the listener always contains false ! Why is that ?

CheckBox layout :

<?xml version="1.0" encoding="utf-8"?>
<CheckBox xmlns:android="http://ift.tt/nIICcg"
    android:id="@android:id/text1"
    style="?android:attr/spinnerDropDownItemStyle"
    android:singleLine="true"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="15dp"
    android:paddingBottom="15dp"
    android:ellipsize="marquee" />




Aucun commentaire:

Enregistrer un commentaire