我已经以编程方式创建了5个无线电组,每组有4个单选按钮。我在我创建的重置按钮上设置了OnClickListener
。我想当有人点击按钮,重新开始我的活动。怎么可能呢?当应用程序第一次启动时,它工作正常,但当我按下按钮重新加载活动时,模拟器崩溃。如果我评论我创建无线电组和单选按钮的行,我按下按钮,活动正在重新加载,否则我有这个错误:Unable to start activity ComponentInfo{...}: java.lang.ArrayIndexOutOfBoundsException: length=4; index=4
。如何在没有问题的情况下重新加载活动?
这是我的代码:
answerGroup = new RadioGroup[5];
answer = new RadioButton[4];
int i = 0;
for (Question qn : questions) {
answerGroup[i] = new RadioGroup(this);
answerGroup[i].setOrientation(RadioGroup.VERTICAL);
int j = 0;
for (Answer an : answers) {
if (qn.getID() == an.getQuestion_id_answer()) {
answer[j] = new RadioButton(this);
answer[j].setText(an.getAnswer());
answerGroup[i].addView(answer[j]);
j++;
}
}
linearLayout.addView(answerGroup[i]);
i++;
}
restartButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = getIntent();
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
startActivity(intent);
}
});
谢谢!
答案 0 :(得分:0)
活动可能尝试引用旧视图元素(从Activity重启之前)。尝试添加您的视图组件:
作为类变量。你能尝试一下并告诉我它在做什么吗?我会根据你给我的输入更新这个答案。
修改强>
我假设您使用ArrayList<Question>
和ArrayList<Answer>
作为questions
和answers
变量。
for (Question qn : questions) {
RadioGroup answerGroup = new RadioGroup(this);
answerGroup.setOrientation(RadioGroup.VERTICAL);
for (Answer an : qn.getAnswers()) {
if (qn.getID() == an.getQuestion_id_answer()) {
RadioButton answer = new RadioButton(this);
answer.setText(an.getAnswer());
answerGroup.addView(answer);
}
}
linearLayout.addView(answerGroup);
}
也许你应该为你的问题添加一个getter方法:getAnswers();
和一个名为Question
的{{1}}模型的变量。当然,在你尝试用它们做任何事情之前,需要先设定这些答案。
答案 1 :(得分:0)
您必须调试代码,可能并非所有您的问题都有4个答案。
如果你的一个问题有超过4个答案(例如:5),并且你试图遍历它们,你会得到 ArrayIndexOutOfBoundsException ,因为j>=4
。
作为解决方案:尝试为List
使用RadioButtons
:
List<RadioButton> answer = new ArrayList<RadioButton>();
对于每次迭代,添加一个新的RadioButton
:
answer.add(new RadioGroup(this));
PS:我还建议你使用recreate()方法重新加载/重新创建你的活动。