Android - 如何检查一个CheckBox取消选中另一个?

时间:2016-01-09 22:58:34

标签: java android

我有两个复选框。如果选中一个,我希望另一个未选中。

代码:

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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>
相关问题