单选按钮未显示正确的值

时间:2012-06-15 04:45:57

标签: android button radio-button

在我的编码中有三个按钮。我得到所选按钮是id并用于比较。但它首先会在单击按钮之前自动显示默认选定按钮的ID。

rdgp.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                counter++;
                if (counter > 5 || counter >= anarray.size()) {
                    Toast.makeText(testActivity.this, "" + score, 2000).show();
                    Intent intent = new Intent(testActivity.this, Badge.class);
                    intent.putExtra("Score", score);
                    startActivity(intent);
                    return;
                }

                rb1.setText(anarray.get(counter));
                rb2.setText(an1array.get(counter));
                rb3.setText(an2array.get(counter));
                rb4.setText(an3array.get(counter));
                rb5.setText(an4array.get(counter));
                int ans = 0;
                if (checkedId == R.id.radio0) {
                    ans = 1;
                } else if (checkedId == R.id.radio1) {
                    ans = 2;
                } else if (checkedId == R.id.radio2) {
                    ans = 3;
                } else if (checkedId == R.id.radio3) {
                    ans = 4;
                }

                Toast.makeText(testActivity.this, "" + ans, 2000).show();
                if (ans == anarray.get(counter))
                    ;
                {
                    score = score + 1;
                }
            }
        });

3 个答案:

答案 0 :(得分:0)

获取已检查radiobutton使用group.getCheckedRadioButtonId()的ID。返回此组中所选单选按钮的标识符。选择空时,返回的值为-1。

答案 1 :(得分:0)

在XML中为所有单选按钮添加以下行。

 android:checked="false"

答案 2 :(得分:0)

如果您从单选按钮获取默认值,请检查我们的布局文件天气您使用的android:checked =“true”。如果这是状态,则将其更改为false。