【问题标题】:How to check if CheckBoxes are empty in an Array?如何检查数组中的复选框是否为空?
【发布时间】:2016-04-19 06:56:06
【问题描述】:

我有几个复选框:

    checkBox1 = (CheckBox)findViewById(R.id.one);
    checkBox2 = (CheckBox)findViewById(R.id.two;
    checkBox3 = (CheckBox)findViewById(R.id.three);
    checkBox4 = (CheckBox)findViewById(R.id.four);
    checkBox5 = (CheckBox)findViewById(R.id.five);
    checkBox6 = (CheckBox)findViewById(R.id.six);
    checkBox7 = (CheckBox)findViewById(R.id.seven);

然后我将它们添加到一个数组中:

    List<CheckBox> checkBoxes = new ArrayList<>();
    CheckBox checkBox;        
    checkBoxes.add(checkBox1); checkBoxes.add(checkBox2);
    checkBoxes.add(checkBox3); checkBoxes.add(checkBox4);
    checkBoxes.add(checkBox5); checkBoxes.add(checkBox6);
    checkBoxes.add(checkBox7);

如果单击按钮时其中一个复选框为空,我想制作一个 Toast。所以我在按钮内使用了一个 for 循环:

public void onButtonClick(){
        for(int i = 0; i <checkBoxes.size(); i++){
            checkBox = checkBoxes.get(i);
        }
       if(!checkBox.isChecked){
            //make Toast "Hey, you didn't check a box"
      }else{
           //do something based on the checked box.
      }
  }

问题是,如果选中了 CheckBox 并且没有执行 else 代码,则 Toast 仍然会显示。 任何帮助将不胜感激,谢谢。

【问题讨论】:

    标签: java android arrays checkbox


    【解决方案1】:

    您的代码仅获得最后一个复选框。你需要在循环中做更多的工作:

    public void onButtonClick() {
        boolean atLeastOneChecked = false;
        for (int i = 0; i < checkBoxes.size(); i++){
            CheckBox checkBox = checkBoxes.get(i);
            if (checkBox.isChecked()) {
                atLeastOneChecked = true;
                break;
            }
        }
        if (!atLeastOneChecked){
            //make Toast "Hey, you didn't check a box"
        } else {
            //do something based on the checked box.
        }
    }
    

    【讨论】:

    • 非常感谢您的快速回答。
    猜你喜欢
    • 1970-01-01
    • 2011-06-10
    • 1970-01-01
    • 2019-07-04
    • 2011-07-02
    • 2011-01-23
    • 2015-02-19
    相关资源
    最近更新 更多