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

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

How can I retrieve a numerical value depending on which radioButton is clicked in this scenario?

问题

  1. @Override
  2. protected void onCreate(Bundle savedInstanceState) {
  3. super.onCreate(savedInstanceState);
  4. setContentView(R.layout.prompts);
  5. radioGroup = (RadioGroup) findViewById(R.id.radioGroup1);
  6. radioGroup.clearCheck();
  7. radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
  8. @Override
  9. public void onCheckedChanged(RadioGroup group, int checkedId) {
  10. RadioButton rb = (RadioButton) group.findViewById(checkedId);
  11. if (null != rb && checkedId > -1) {
  12. int buttonIndex = Integer.parseInt(rb.getTag().toString());
  13. Toast.makeText(MainActivity.this, String.valueOf(buttonIndex), Toast.LENGTH_SHORT).show();
  14. }
  15. }
  16. });
  17. }
英文:
  1. @Override
  2. protected void onCreate(Bundle savedInstanceState) {
  3. super.onCreate(savedInstanceState);
  4. setContentView(R.layout.prompts);
  5. radioGroup = (RadioGroup) findViewById(R.id.radioGroup1);
  6. radioGroup.clearCheck();
  7. radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
  8. @Override
  9. public void onCheckedChanged(RadioGroup group, int checkedId) {
  10. RadioButton rb = (RadioButton) group.findViewById(checkedId);
  11. if(null!=rb && checkedId > -1){
  12. Toast.makeText(MainActivity.this, rb.getText(), Toast.LENGTH_SHORT).show();
  13. }
  14. }
  15. });
  16. }

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

尝试这个:

  1. int btnCheck;
  2. radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
  3. public void onCheckedChanged(RadioGroup group, int checkedId) {
  4. switch(checkedId){
  5. case R.id.radio1:
  6. btnCheck=0;
  7. break;
  8. case R.id.radio2:
  9. btnCheck=1;
  10. break;
  11. case R.id.radio3:
  12. btnCheck=2;
  13. break;
  14. }
  15. }
英文:

Try this:

  1. int btnCheck;
  2. radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
  3. public void onCheckedChanged(RadioGroup group, int checkedId) {
  4. switch(checkedId){
  5. case R.id.radio1:
  6. btnCheck=0;
  7. break;
  8. case R.id.radio2:
  9. btnCheck=1;
  10. break;
  11. case R.id.radio2:
  12. btnCheck=2;
  13. break;
  14. }
  15. }

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:

确定