如何根据所点击的单选按钮来检索数值?

huangapple go评论67阅读模式
英文:

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;
     }
}

huangapple
  • 本文由 发表于 2020年4月7日 04:15:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/61068226.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定