我已经实际创建了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++;
}
谢谢!
答案 0 :(得分:0)
在日志中:
ArrayIndexOutOfBoundsException:length = 4;索引= 4
因为答案数组的大小为j
而不是i
,所以将RadioButton点击侦听器移到for循环中:
for (Answer an : answers) {
if (qn.getID() == an.getQuestion_id_answer()) {
answer[j] = new RadioButton(this);
...your code here...
answer[j].setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// your code here...
}
});
j++;
}
}