【发布时间】:2015-11-07 02:38:11
【问题描述】:
我实用地创建了 5 个单选组,每个组有 4 个单选按钮。如何获取单选按钮的 ID?非常重要,我不想使用 setOnCheckedChangeListener。这是我的代码。
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]);
j++;
}
}
linearLayout.addView(radioGroup[i]);
answer[i].setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int checkedRadioButtonId = v.getId();
RadioButton checkedRadioButton = (RadioButton) findViewById(checkedRadioButtonId);
if (checkedRadioButton.isChecked()) {
Toast.makeText(getApplicationContext(), "Checkbox" + checkedRadioButtonId + " checked", Toast.LENGTH_SHORT).show();
}
}
});
i++;
}
谢谢!
【问题讨论】:
-
使用当前代码有什么问题?
-
错误是:
Unable to start activity ComponentInfo{com.example.alexm.iq_test_final/com.example.alexm.iq_test_final.MainActivity}: java.lang.ArrayIndexOutOfBoundsException: length=4; index=4 -
您的数组太小,无法填充它。将答案的大小增加到 5 或减少您的人口。您的问题在错误中是正确的。 java.lang.ArrayIndexOutOfBoundsException:长度=4;索引=4
标签: java android loops for-loop radio-button