尝试在选中时取消选择RadioButton。我被建议使用
RadioGroup radioGroup = (RadioGroup)findViewById(R.id.Radio_Group);
radioGroup.clearCheck();
但是当我在我的代码中使用它时会阻止所有RadioButton,因此无法选择它们。
public void OnRadioButtonClick(View view)
{
boolean checked = ((RadioButton) view).isChecked();
switch (view.getId()) {
case radioButton1:
Toast.makeText(MainActivity.this, "..." + String.valueOf(checked),
Toast.LENGTH_SHORT).show();
break;
case R.id.radioButton2:
Toast.makeText(MainActivity.this, "..." + String.valueOf(checked),
Toast.LENGTH_SHORT).show();
break;
case R.id.radioButton3:
Toast.makeText(MainActivity.this, "...." + String.valueOf(checked),
Toast.LENGTH_SHORT).show();
break;
}
}
请在解释中使用简单的语言:)我是编程新手。 感谢。
答案 0 :(得分:0)
使用.setChecked(false);
。
例如:
//global variable, inside a class
boolean wasChecked;
public void OnRadioButtonClick(View view){
boolean checked = ((RadioButton) view).isChecked();
if(wasChecked && checked){
((RadioButton) view).setChecked(false);
wasChecked = false;
}else if(checked){
wasChecked = true;
}
// ...
}
以下是完整的解决方案:
boolean wasChecked;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void OnRadioButtonClick(View view)
{
boolean checked = ((RadioButton) view).isChecked();
if(wasChecked && checked){
((RadioButton) view).setChecked(false);
wasChecked = false;
}else if(checked){
wasChecked = true;
}
switch (view.getId()) {
case R.id. radioButton1:
Toast.makeText(MainActivity.this, "..." + String.valueOf(checked),
Toast.LENGTH_SHORT).show();
break;
case R.id.radioButton2:
Toast.makeText(MainActivity.this, "..." + String.valueOf(checked),
Toast.LENGTH_SHORT).show();
break;
case R.id.radioButton3:
Toast.makeText(MainActivity.this, "...." + String.valueOf(checked),
Toast.LENGTH_SHORT).show();
break;
}
}