mardi 10 novembre 2015

How to set text color of a text when a button is pressed in Java?

I have created programmatically, 5 radio groups with 4 radio buttons each. Every radio button represents an answer to a question. I want when someone press the button, if the correct answer is checked, to set the color of the that text in green. What am i trying to do, is to know in the second OnClickListener which radio button was checked, and if it is the correct one, to make the text green. So, with this code, when i press the button, nothing happens. If i remove the condition if (CorrectAnswer == 1) and i press the button, i get this error: Attempt to invoke virtual method 'void android.widget.RadioButton.setTextColor(int)' on a null object reference. Any ideas? Here is my code:

boolean isChecked;
RadioButton checkedRadioButton;
RadioGroup radioButtonGroup;
int CorrectAnswer;

radioGroup[i].addView(answer[j]);

answer[j].setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        checkedRadioButton = ((RadioButton) v);
        int CorrectAnswer = Integer.parseInt(checkedRadioButton.getTag().toString());
        isChecked = true;
        if (isChecked) {
            if (checkedRadioButton.isChecked() & CorrectAnswer == 1) {
                score++;
                isChecked = false;
            }
        }
    }
});

finishButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        for (int i = 0; i < radioGroup.length; i++) {
            int radioGroupId = radioGroup[i].getId();
            radioButtonGroup = (RadioGroup) findViewById(radioGroupId);
            int checkedRadioButtonId = radioButtonGroup.getCheckedRadioButtonId();
            checkedRadioButton = (RadioButton) findViewById(checkedRadioButtonId);
            if (CorrectAnswer == 1) {
                checkedRadioButton.setTextColor(Color.GREEN);
            }
            for (int j = 0; j < answer.length; j++) {
                radioGroup[i].getChildAt(j).setEnabled(false);
            }
        }
    }
});

Thanks!

Aucun commentaire:

Enregistrer un commentaire