簡體   English   中英

在Java中按下按鈕時如何設置文本的文本顏色?

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

我以編程方式創建了5個無線電組,每個組有4個單選按鈕。 每個單選按鈕代表一個問題的答案。 我想當有人按下按鈕時,如果檢查了正確答案,則以綠色設置該文本的顏色。 我想做的是,在第二個OnClickListener知道OnClickListener哪個單選按鈕,如果它是正確的,則使文本變為綠色。 因此,使用此代碼,當我按下按鈕時,什么也沒有發生。 如果我刪除條件if (CorrectAnswer == 1)並按下按鈕, if (CorrectAnswer == 1)收到此錯誤: Attempt to invoke virtual method 'void android.widget.RadioButton.setTextColor(int)' on a null object reference 有任何想法嗎? 這是我的代碼:

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

謝謝!

這樣做可以避免在空引用上調用方法。

if (CorrectAnswer == 1 && checkedRadioButton  != null) 

編輯:

將語句更改為此

if (checkedRadioButton  != null && Integer.parseInt(checkedRadioButton.getTag().toString()) == 1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM