如何获取Java中单选按钮的id?

How to get the id of a radio button in Java?

我已经实用地创建了 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++;
    }

谢谢!

如日志中所示:

ArrayIndexOutOfBoundsException: length=4; index=4

因为答案数组的大小是 j 而不是 i,所以将 RadioButton click listener 移动到循环中:

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++;
     }
}