我已经实际创建了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++;
}
谢谢!
答案 0 :(得分: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);
RadioGroup
请求的ID' checkedRadioButtonId
'首先找到。这会导致崩溃。
要解决此问题,请使用tag属性,例如
radioGroup[i].setTag("rg" + i);
和answer[j].setTag("rb" + j);
然后,您可以使用标记" xyz"来获取个人View
通过写作
RadioButton checkedRadioButton = (RadioButton) findViewWithTag("xyz");