我有一个单选按钮组,有四个单选按钮。我正在尝试创建一个场景,当用户点击单选按钮时,该单选按钮的值将显示给他。但我的代码无效。
这是我的单选按钮组,调用onclick侦听器
buttongroup.setOnClickListener(buttongroupListener);
上面的行放在onCreate View中。
private OnClickListener buttongroupListener = new OnClickListener(){
@Override
public void onClick(View view) {
// TODO Auto-generated method stub
String selectedValue = "";
// Is the button now checked?
if(view.getId() == R.id.buttoncontainer){
boolean checked = ((RadioButton) view).isChecked();
int selectedRadioID = buttongroup.getCheckedRadioButtonId();
if(checked){
switch(selectedRadioID){
case R.id.radioButton1:
selectedValue = "A";
break;
case R.id.radioButton2:
selectedValue = "B";
break;
case R.id.radioButton3:
selectedValue = "C";
break;
case R.id.radioButton4:
selectedValue = "D";
break;
}
}
}
Toast.makeText(context, selectedValue,Toast.LENGTH_SHORT).show();
}
};
答案 0 :(得分:1)
我建议的更好的选择是使用RadioGroup
事件如下:
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.yourRadioGroup);
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch(checkedId){
case R.id.radioButton1:
selectedValue = "A";
break;
case R.id.radioButton2:
selectedValue = "B";
break;
case R.id.radioButton3:
selectedValue = "C";
break;
case R.id.radioButton4:
selectedValue = "D";
break;
}
}Toast.makeText(context, selectedValue,Toast.LENGTH_SHORT).show();
});