【发布时间】:2015-11-11 10:17:54
【问题描述】:
我以编程方式创建了 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);
}
});
谢谢!
【问题讨论】:
-
请提供所有logcat
-
它在 logcat 中显示了什么
-
是的,你是对的。这是我的entire logcat
-
也许
questions数组比answerGroup数组大。您正在通过questions数组的每次迭代更改i,但您正在使用它来访问answerGroup数组中的元素。answer数组也是如此。 -
您的问题列表的大小是多少?看起来超过4。如果超过4,那么它会分配j=4,这会给出一个arrayindexoutofboundsexception。
标签: java android loops android-activity onclicklistener