2016-01-14 44 views
0

我有一對夫婦的複選框:如何檢查數組中的CheckBox是否爲空?

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); 

我想敬酒,如果其中一個複選框上點擊一個按鈕空。所以我用一個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. 
     } 
    } 

的問題是,如果一個複選框被選中仍被顯示的麪包和它不執行其他代碼。 任何幫助,將不勝感激,謝謝。

回答

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. 
    } 
} 
+0

非常感謝你的快速回答。 –