【问题标题】:How to get the id of a radio button in Java?如何在 Java 中获取单选按钮的 id?
【发布时间】: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


【解决方案1】:

如日志:

ArrayIndexOutOfBoundsException: 长度=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++;
     }
}

【讨论】:

  • 不起作用。这是错误:java.lang.ClassCastException: android.widget.RadioGroup cannot be cast to android.widget.RadioButton。可以做什么?
  • @AlexM.: 在哪一行得到它?请分享最新代码和完整日志
  • 这是我的代码:link,这是错误:link
  • @AlexM.: 第 119 行是什么?
  • 这是第 119 行:RadioButton checkedRadioButton = (RadioButton) findViewById(checkedRadioButtonId);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-22
  • 1970-01-01
  • 2015-09-09
  • 2020-07-25
  • 2011-07-28
  • 1970-01-01
相关资源
最近更新 更多