如何清除所有无线电组和setTextColor到Java中只有一个单选按钮?

时间:2015-11-05 08:03:47

标签: java android loops for-loop onclicklistener

我用2个单选按钮动态创建了2个无线电组。每个单选按钮代表一个问题的答案。我使用setOnCheckedChangeListener来查看哪些anwsers是正确的。因此,当我按下按钮时,我希望拥有所有广播组clearCheck()以及正确答案setTextColor(Color.GREEN)。使用此代码,当我使用radioGroup[i].clearCheck();时,我收到此错误:Attempt to invoke virtual method 'java.lang.Object android.widget.RadioButton.getTag()' on a null object reference。我怎样才能解决这个问题?我怎样才能将文字颜色设置为绿色,只有正确的答案?这是我的代码:

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

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton checkedRadioButton = (RadioButton)group.findViewById(checkedId);
                int  CorrectAnswer = Integer.parseInt(checkedRadioButton.getTag().toString());
                switch (checkedId) {
                    case 0:
                        if (CorrectAnswer == 1) {
                            Toast.makeText(getApplicationContext(), "You clicked the correct answer ", Toast.LENGTH_SHORT).show();
                            score++;
                        } 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();
                            score++;
                        } else {
                            Toast.makeText(getApplicationContext(), "You clicked the incorrect answer ", Toast.LENGTH_SHORT).show();
                        }
                        break;
                }
            }
        });

        resetButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (int i = 0; i < radioGroup.length; i++) {
                    radioGroup[i].clearCheck(); // doesn't work
                    for (int j = 0; j < answer.length; j++) {
                        radioGroup[i].getChildAt(j).setBackgroundColor(Color.WHITE);
                        ((RadioButton) radioGroup[i].getChildAt(j)).setTextColor(Color.GREEN);
                    }
                }
            }
        });

谢谢!

1 个答案:

答案 0 :(得分:0)

在调用onCheckedChanged方法时,可能会调用clearCheck方法,因此在null方法上调用onCheckedChanged方法之前,请先toString()加入setTag

@Override
  public void onCheckedChanged(RadioGroup group, int checkedId) {
      RadioButton checkedRadioButton = (RadioButton)group.findViewById(checkedId);
      if(checkedRadioButton!=null)
      if(checkedRadioButton.getTag() !=null){
        int  CorrectAnswer = Integer.parseInt(
                         checkedRadioButton.getTag().toString());
          ....your code here

       } 
    }