列表中的复选框在单击时显示检查,但isChecked()未更改(Android)

时间:2015-07-20 05:28:32

标签: android checkbox

我有一个复选框列表(通过自定义列表适配器创建),其中一些复选框根据存储的数据开始检查。当用户按下另一个按钮时,我想检查哪些框被选中。现在它从两个盒子开始,其中一个被点击。当我单击复选框时,UI会相应更改,但当我执行“收集已检查”功能时,它会报告原始配置,而不是更改的配置。

行的XML:

CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Default"
android:id="@+id/cause_checkbox"
xmlns:android="http://schemas.android.com/apk/res/android"

列表适配器:     private class CauseEntryAdapter extends ArrayAdapter {         列出selectedCauseKeys;         列出availableCauseKeys;

    public CauseEntryAdapter(Context context, List<String> causeLabels, List<String> availableCauseKeys, List<String> selectedCauseKeys) {
        super(context, 0, causeLabels);
        if (selectedCauseKeys != null)
            this.selectedCauseKeys = selectedCauseKeys;
        else
            this.selectedCauseKeys = new LinkedList<>();

        this.availableCauseKeys = availableCauseKeys;
    }

    public View getView(int position, View convertView, ViewGroup parent) {

        String cause = (String) getItem(position);
        if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.cause_list_item, parent, false);

        }
        CheckBox checkbox = (CheckBox) convertView.findViewById(R.id.cause_checkbox);
        checkbox.setText(cause);
        checkbox.setChecked(selectedCauseKeys.contains(availableCauseKeys.get(position)));

        return convertView;
    }
}

收集复选框的代码:

public List<String> getCheckedCauses() {
    List<String> ret = new LinkedList<String>();
    for(int i = 0; i< mAdapter.getCount(); i++) {
        CheckBox checkBox =  (CheckBox) mAdapter.getView(i, null, null).findViewById(R.id.cause_checkbox);
        if (checkBox.isChecked()) {
            ret.add((String) mAdapter.getItem(i));
        }
        //TODO why is this picking up preferences not the list?
    }
    return ret;
}

列表存在于片段中,我用:

调用它
CauseListFragment causeListFragment = (CauseListFragment)  fragmentManager.getFragments().get(0);
return causeListFragment.getCheckedCauses();

1 个答案:

答案 0 :(得分:0)

这是因为你的getCheckedCauses方法要求适配器通过调用getView方法告诉他复选框的状态,该方法依赖于你传递给适配器的原始状态。

在适配器中,一个解决方案可能是在复选框上设置侦听器,并在每次单击复选框时更新availableCauseKey列表。

编辑:或者更简单,在你的适配器中有一个isBoxChecked()方法,如下所示:

public boolean isBoxChecked(int viewId){
    View convertView = LayoutInflater.from(getContext()).inflate(R.layout.cause_list_item, parent, false);
    CheckBox checkbox = (CheckBox) convertView.findViewById(R.id.cause_checkbox);
    return checkBox.isChecked();
    }
相关问题