英文:
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;
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论