2016-01-09 32 views
0

我有兩個複選框。如果有人被選中,我想讓其他人不被選中。Android - 如何檢查一個CheckBox取消選中另一個?

代碼:

CheckBox ozCheckBox = (CheckBox)findViewById(R.id.oz); 
    boolean ozInput = ozCheckBox.isChecked(); 
    CheckBox gCheckBox = (CheckBox)findViewById(R.id.g); 
    boolean gInput = gCheckBox.isChecked(); 
+1

你應該看看'RadioGroup'和'RadioButton',因爲這些行爲都是這些行爲所期望的,而不是來自'Checkbox' –

回答

0

使用此:

if(ozCheckBox.isChecked()) //Check if first is checked 
{ 
    //Set uncheck to second 
    gInput.setChecked(false); 
} 
else 
{ 
    //Set checked to second 
    gInput.setChecked(true); 
} 

更準確:

ozCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() { 
@Override 
public void onCheckedChanged(RadioGroup group, int checkedId) { 
if(ozCheckBox.isChecked()) //Check if first is checked 
{ 
    //Set uncheck to second 
    gInput.setChecked(false); 
} 
else 
{ 
    //Set checked to second 
    gInput.setChecked(true); 
} 
} 
}); 

在這裏看到更多的建議CheckBox

0

爲什麼不使用單選按鈕和廣播組目的? 這可以使用兩個RadioButton ina RadioGroup完成。您可以將RadioButton設計爲CheckBox

 <RadioGroup 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:checkedButton="@+id/two"> 

      <RadioButton 
       android:id="@+id/one" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:button="?android:attr/listChoiceIndicatorMultiple" 
       android:text="CheckBox One" /> 

      <RadioButton 
       android:id="@+id/two" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:button="?android:attr/listChoiceIndicatorMultiple" 
       android:text="CheckBox Two" /> 
     </RadioGroup> 
相關問題