【发布时间】: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);
}
}
}
});
谢谢!
【问题讨论】:
-
我会说
checkedRadioButton是null。 -
好的,但是我能做些什么来解决这个问题?
-
检查 null ... 但这只会防止异常。您需要弄清楚,为什么 findByViewId 找不到 getCheckedRadioButtonId 返回的 ID。
-
我怎样才能弄清楚?
-
因为如果没有检查,
radioButtonGroup.getCheckedRadioButtonId();会返回-1。
标签: java android loops if-statement onclicklistener