此代码是选中复选框1 + 2的复选框

时间:2014-02-17 05:43:01

标签: android checkbox

    if (q1.isChecked()) {
        int count = 0;
        for (CheckBox cb : cbList) {
            if (cb.isChecked()) {
                count++;
            }
        }
        if (count <= 2) {
            //this Toast will show when only 1 or 2 checkbox will be checked
            Toast.makeText(getApplicationContext(), getString(R.string.negative), Toast.LENGTH_SHORT).show();
        } else {
            if(count > 2) {
        }
            //this Toast will show when more than 2 checkboxs will be checked
            Toast.makeText(getApplicationContext(), getString(R.string.positive), Toast.LENGTH_SHORT).show();
        }
    }

代码出了什么问题..无论我改变了什么值......在3个复选框中仍然显示为负数而不是正数

2 个答案:

答案 0 :(得分:0)

假设您已正确实施CheckableLayout(用于单个选择或多个选择),您可以调整您的代码,如下所示,以实现您可能想要的

...
 // Looping if CheckBox number 1 is not selected and the others are not
 // Get an array that tells us for each position whether the item is
 // checked or not
 // --

final SparseBooleanArray checkedItems = listView.getCheckedItemPositions();
        if (checkedItems.size() == 0) {
            Toast.makeText(this, "No selection info available", Toast.LENGTH_LONG).show();
            return;
        }

答案 1 :(得分:0)

我根据你的问题理解我的答案......可能是你在寻找这种解决方案...

if (q1.isChecked()) {
    int count = 0;
    for (CheckBox cb : cbList) {
        if (cb.isChecked()) {
            count++;
        }
    }
    if (count <= 2) {
        //this dialog will show when only 1 or 2 checkbox will be checked
        new AlertDialog.Builder(this).setMessage(getString(R.string.negative)).show();
    } else {
        //this dialog will show when more than 2 checkboxs will be checked
        new AlertDialog.Builder(this).setMessage(getString(R.string.positive)).show();
    }
}

现在我的建议是,如果您只是想在对话框中显示消息而没有任何按钮可以根据该消息采取进一步的操作,那么您应该使用Toast。通常,Toast会帮助您短时间或长时间在屏幕上显示您的信息。我还用Toast ...

给你代码
if (q1.isChecked()) {
    int count = 0;
    for (CheckBox cb : cbList) {
        if (cb.isChecked()) {
            count++;
        }
    }
    if (count <= 2) {
        //this Toast will show when only 1 or 2 checkbox will be checked
        Toast.makeText(getApplicationContext(), getString(R.string.negative), Toast.LENGTH_SHORT).show();
    } else {
        //this Toast will show when more than 2 checkboxs will be checked
        Toast.makeText(getApplicationContext(), getString(R.string.positive), Toast.LENGTH_SHORT).show();
    }
}