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

android.widget.RadioGroup cannot be cast to android.widget.RadioButton

我已经实用地创建了 5 个单选组,每个单选组有 4 个单选按钮。当我尝试使用 checkedRadioButton 时,模拟器崩溃了吗?错误是:android.widget.RadioGroup cannot be cast to android.widget.RadioButton。我哪里错了?

这是我的代码:

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

您正在通过

以编程方式设置 RadioGroupRadioButton 视图的 ID
radioGroup[i].setId(i);

分别

answer[j].setId(j);

因为 i 的某些值也可以是 j 的值(例如 i=j=0),所以有时您会两次分配相同的 ID。

方法 findViewById() 将 return 任何具有匹配 id 的 View,returned View 仅在转换为适当的 class.

现在不小心上线了

RadioButton checkedRadioButton = (RadioButton) findViewById(checkedRadioButtonId);

首先找到请求 ID 为“checkedRadioButtonId”的 RadioGroup。这会导致崩溃。

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

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

然后你可以通过写

得到标签"xyz"的个体View
RadioButton checkedRadioButton = (RadioButton) findViewWithTag("xyz");