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

问题描述 投票:2回答:1

我用实际创建了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++;
    }

谢谢!

java android loops radio-button onclicklistener
1个回答
1
投票

您正在以编程方式设置RadioGroup以及RadioButton视图的ID

radioGroup[i].setId(i);

分别

answer[j].setId(j);

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

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

现在不小心在线

RadioButton checkedRadioButton = (RadioButton) findViewById(checkedRadioButtonId);

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

要解决此问题,请使用tag属性

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

然后你可以通过写作获得带有标签“xyz”的个人View

RadioButton checkedRadioButton = (RadioButton) findViewWithTag("xyz");
© www.soinside.com 2019 - 2024. All rights reserved.