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
的ID以及RadioButton
视图
radioGroup[i].setId(i);
分别
answer[j].setId(j);
因为i的某些值也可以是j的值(例如i = j = 0),所以有时会将相同的id分配两次。
方法findViewById()
将返回任何具有匹配id的View
,返回的View
仅在该类型转换为相应的类之后。
现在不小心在线
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");