android.widget.RadioGroup 无法转换为 android.widget.RadioButton

我实用地创建了 5 个单选组,每个组有 4 个单选按钮.当我尝试使用 checkedRadioButton 时,模拟器会崩溃?错误是:android.widget.RadioGroup 无法转换为 android.widget.RadioButton.我错了吗?这是我的代码:

I've created pragmatically 5 radio groups with 4 radio buttons each. When i am trying to use checkedRadioButton the emulator crushes? The error is: android.widget.RadioGroup cannot be cast to android.widget.RadioButton. Were am i wrong? Here is my code:

    radioGroup = new RadioGroup[5];
    answer = new RadioButton[4];
    int i = 0;
    for (Question qn : questions) {
        radioGroup[i] = new RadioGroup(this);
        radioGroup[i].setId(i);
        int j = 0;
        for (Answer an : answers) {
            if (qn.getID() == an.getQuestion_id_answer()) {
                answer[j] = new RadioButton(this);
                answer[j].setText(an.getAnswer());
                answer[j].setId(j);
                radioGroup[i].addView(answer[j]);

                answer[j].setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        int checkedRadioButtonId = v.getId();
                        Toast.makeText(getApplicationContext(), "Checkbox" + checkedRadioButtonId + " checked", Toast.LENGTH_SHORT).show();
                        RadioButton checkedRadioButton = (RadioButton) findViewById(checkedRadioButtonId);
                    }
                });
                j++;
            }
        }
        linearLayout.addView(radioGroup[i]);
        i++;
    }

谢谢!

推荐答案

您正在为 RadioGroup 以及 RadioButton 视图设置 id 由

You are setting the id for the RadioGroup as well as the RadioButton views programmatically by

radioGroup[i].setId(i);

分别

answer[j].setId(j);

由于 i 的某些值也可以是 j 的值(例如 i=j=0),因此您有时会分配相同的 id 两次.

Because some values of the i's can also be values for the j's (e.g. i=j=0), you sometimes assign the same id twice.

findViewById() 方法将返回任何具有匹配 id 的 View,返回的 View 仅在转换为适当的类之后.

The method findViewById() will return any View with matching id, the returned View is only after that cast to the appropriate class.

现在不小心排队了

RadioButton checkedRadioButton = (RadioButton) findViewById(checkedRadioButtonId);

首先找到具有请求 id 'checkedRadioButtonId' 的 RadioGroup.这会导致崩溃.

the RadioGroup with the requested id 'checkedRadioButtonId' is found first. This causes the crash.

解决问题,使用tag属性,例如

To solve the problem, use the tag attribute, for example

radioGroup[i].setTag("rg" + i);answer[j].setTag("rb" + j);

然后你可以通过写得到带有标签xyz"的单个View

Then you can get the individual View with tag "xyz" by writing

RadioButton checkedRadioButton = (RadioButton) findViewWithTag("xyz");

相关文章