英文:
How can I retrieve a numerical value depending on which radioButton is clicked in this scenario?
问题
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.prompts);
radioGroup = (RadioGroup) findViewById(R.id.radioGroup1);
radioGroup.clearCheck();
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton rb = (RadioButton) group.findViewById(checkedId);
if (null != rb && checkedId > -1) {
int buttonIndex = Integer.parseInt(rb.getTag().toString());
Toast.makeText(MainActivity.this, String.valueOf(buttonIndex), Toast.LENGTH_SHORT).show();
}
}
});
}
英文:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.prompts);
radioGroup = (RadioGroup) findViewById(R.id.radioGroup1);
radioGroup.clearCheck();
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton rb = (RadioButton) group.findViewById(checkedId);
if(null!=rb && checkedId > -1){
Toast.makeText(MainActivity.this, rb.getText(), Toast.LENGTH_SHORT).show();
}
}
});
}
Currently the toast will show whatever text is associated with the specific button. I have a stack of 6 buttons and would like instead to retrive an integer from 0-5 depending on which button is clicked
答案1
得分: 0
尝试这个:
int btnCheck;
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch(checkedId){
case R.id.radio1:
btnCheck=0;
break;
case R.id.radio2:
btnCheck=1;
break;
case R.id.radio3:
btnCheck=2;
break;
}
}
英文:
Try this:
int btnCheck;
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch(checkedId){
case R.id.radio1:
btnCheck=0;
break;
case R.id.radio2:
btnCheck=1;
break;
case R.id.radio2:
btnCheck=2;
break;
}
}
专注分享java语言的经验与见解,让所有开发者获益!
评论