最是人间留不住,朱颜辞镜花辞树。这篇文章主要讲述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
视图的IDradioGroup[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");
推荐阅读
- RadioButton Intent活动 - android
- Android(onResume更新单选按钮)
- 添加值,更改单击单选按钮android
- 在其线性布局垂直父Android中将以编程方式创建的单选按钮居中
- 如何将RadioGroup元素的ID转换为Android studio中的字符串()
- 一般故障建设bootstrapper
- Android Studio中的Admob非页内广告无效
- 重新打开PowerApps后我无法从PowerBi Integration检索数据
- 如何将浮动操作按钮锚定到App ToolBar,就像在指南图像中一样()