如何在Java中检查不同的单选按钮时显示不同的消息?

时间:2015-11-04 21:03:29

标签: java android if-statement for-loop changelistener

我想显示“你点击了错误的答案”,当选中第一个单选按钮时,“你点击了正确答案”,当选中第二个单选按钮时。使用此代码,我收到错误:Cannot resolve symbol 'CorrectAnswer'。可靠的CorrectAnswer是数据库查询的结果。这是我的代码:

    radioGroup = new RadioGroup[2];
    answer = new RadioButton[2];
    int i = 0;
    for (Question qn : questions) {
        radioGroup[i] = new RadioGroup(this);
        int j = 0;
        for (Answer an : answers) {
            if (qn.getID() == an.getQuestion_id_answer()) {
                String answers_log = " " + an.getAnswer();
                Integer CorrectAnswer = an.getCorrect_answer();
                answer[j] = new RadioButton(this);
                answer[j].setText(answers_log);
                radioGroup[i].addView(answer[j]);
                j++;
            }
        }
        linearLayout.addView(radioGroup[i]);

        radioGroup[i].setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case 0:
                        if (CorrectAnswer == 1) {
                            Toast.makeText(getApplicationContext(), "You clicked the correct answer ", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(getApplicationContext(), "You clicked the incorrect answer ", Toast.LENGTH_SHORT).show();
                        }
                        break;
                    case 1:
                        if (CorrectAnswer == 1) {
                            Toast.makeText(getApplicationContext(), "You clicked the correct answer ", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(getApplicationContext(), "You clicked the incorrect answer ", Toast.LENGTH_SHORT).show();
                        }
                        break;
                }
            }
        });
        i++;
    }

数据库结构如下:

         db.addAnswer(new Answer("NY", 3, 0));
         db.addAnswer(new Answer("WA", 3, 1));

如你所见,在第三栏中我有1,这意味着第二个答案是真的 谢谢!

1 个答案:

答案 0 :(得分:1)

  

我收到错误:无法解析符号' CorrectAnswer'

因为CorrectAnswer变量不在尝试访问它的方法范围内。

将其声明为全局变量或使用setTag/getTag的{​​{1}}来获取RadioButton

中的CorrectAnswer

我认为使用setTag / getTag方法将onCheckedChanged设置为:

1。首先使用CorrectAnswer保存值RadioButton

setTag

2。answer[j] = new RadioButton(this); answer[j].setTag(String.valueOf(an.getCorrect_answer())); answer[j].setText(answers_log); 中选择onCheckedChanged值为:

RadioButton