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

最是人间留不住,朱颜辞镜花辞树。这篇文章主要讲述android.widget.RadioGroup无法强制转换为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++; }

谢谢!
答案您正在以编程方式设置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);
【android.widget.RadioGroup无法强制转换为android.widget.RadioButton】然后你可以通过写作获得带有标签“xyz”的个人View
RadioButton checkedRadioButton = (RadioButton) findViewWithTag("xyz");


    推荐阅读