【问题标题】:How to set text color of a text when a button is pressed in Java?在Java中按下按钮时如何设置文本的文本颜色?
【发布时间】:2023-03-21 13:34:02
【问题描述】:

我以编程方式创建了 5 个单选组,每个组有 4 个单选按钮。每个单选按钮都代表一个问题的答案。我希望当有人按下按钮时,如果检查了正确答案,则将该文本的颜色设置为绿色。我想做的是在第二个OnClickListener 中知道哪个单选按钮被选中,如果它是正确的,则使文本变为绿色。因此,使用此代码,当我按下按钮时,什么也没有发生。如果我删除条件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);
            }
        }
    }
});

谢谢!

【问题讨论】:

  • 我会说checkedRadioButtonnull
  • 好的,但是我能做些什么来解决这个问题?
  • 检查 null ... 但这只会防止异常。您需要弄清楚,为什么 findByViewId 找不到 getCheckedRadioButtonId 返回的 ID。
  • 我怎样才能弄清楚?
  • 因为如果没有检查,radioButtonGroup.getCheckedRadioButtonId(); 会返回 -1

标签: java android loops if-statement onclicklistener


【解决方案1】:

这样做是为了避免在空引用上调用方法。

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

编辑:

把语句改成这样

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

【讨论】:

  • 还不错,但是当我按下按钮时,我的文字仍然是黑色,而不是绿色。
  • @AlexM。你在哪里设置 CorrectAnswer?
  • 在第一个OnClickListener,你看我有int CorrectAnswer = Integer.parseInt(checkedRadioButton.getTag().toString());
  • @AlexM。因此,对于所有无线电组,您基本上都有一个变量。如果在错误的标签上选中了其中一​​个单选按钮,则正确答案将不是 1,因此 if 语句将永远不会为真。为避免这种情况,请为每个单选组创建一个单独的字段或将所有单选按钮检查到正确的单选按钮
  • 这可以防止在空引用上调用方法,但是当我按下按钮时,文本仍然是黑色的,而不是绿色的。如何检查所有单选按钮是否正确?
猜你喜欢
  • 1970-01-01
  • 2015-12-07
  • 2020-11-07
  • 1970-01-01
  • 1970-01-01
  • 2012-09-10
  • 2015-05-11
  • 2015-04-17
  • 1970-01-01
相关资源
最近更新 更多