如何取消选中以前选中的复选框,反之亦然。我正在尝试开发一个应用程序,检查您只能选择两个选项之一。我似乎无法让onCheckedChangeListener工作。我不想要单选按钮,因为它们无法被取消。
我尝试了Noob发布的类似问题的代码。 I need to uncheck a checkbox when a particular checkbox is checked
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setalarm);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final CheckBox chk1 = (CheckBox) findViewById(R.id.checkBox1);
final CheckBox chk2 = (CheckBox) findViewById(R.id.checkBox2);
chk1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
chk2.setChecked(false);
}
});
chk2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
chk1.setChecked(false);
}
});
}
答案 0 :(得分:0)
如果您确定不想使用RadioButton
并且只有两个可能的CheckBox
选项,那么这样的简单应该可以解决问题:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_name);
final CheckBox c1 = (CheckBox) findViewById(R.id.c1);
final CheckBox c2 = (CheckBox) findViewById(R.id.c2);
c1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
c2.setChecked(false);
c1.setChecked(b);
}
});
c2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
c1.setChecked(false);
c2.setChecked(b);
}
});
}