gpt4 book ai didi

java - 如何在Java中为ArrayList中的所有元素设置文本颜色?

转载 作者:行者123 更新时间:2023-12-01 10:55:17 25 4
gpt4 key购买 nike

我以编程方式创建了 5 个单选组,每个组有 4 个单选按钮。每个单选按钮代表一个问题的答案。所以我想这样做。当有人检查 radio 组中的正确答案时,我想将所有答案添加到名为 CorrectAnswerRadios ArrayList 中。与错误答案相同。我还在按钮上设置了一个 OnClickListener 。当有人按下按钮时,我还想将所有正确答案设为绿色,将错误答案设为红色。使用此代码,我收到此错误:“java.lang.NullPointerException:尝试写入空数组”。

这是我的代码:

RadioGroup[] answerGroup;
RadioButton[] answer;
Button finishButton;
RadioButton[] checkedRadioButton;
ArrayList<RadioButton> correctAnswerRadios;
ArrayList<RadioButton> wrongAnswersRadios;

correctAnswerRadios = new ArrayList<>();
wrongAnswersRadios = new ArrayList<>();
answerGroup = new RadioGroup[5];
answer = new RadioButton[4];

int i = 0;
for (Question qn : questions) {
answerGroup[i] = new RadioGroup(this);
int j = 0;
for (Answer an : answers) {
if (qn.getID() == an.getQuestion_id_answer()) {
answer[j] = new RadioButton(this);
answer[j].setText(an.getAnswer());
answer[j].setId(j + 100);
answer[j].setTag(String.valueOf(an.getCorrect_answer()));
answerGroup[i].addView(answer[j]);

answer[j].setOnClickListener(new View.OnClickListener() {
private boolean isChecked = true;
@Override
public void onClick(View v) {
for (int j = 0; j < answer.length; j++) {
checkedRadioButton[j] = ((RadioButton) v);
int CorrectAnswer = Integer.parseInt(checkedRadioButton[j].getTag().toString());
if (checkedRadioButton[j].isChecked() & CorrectAnswer == 1) {
correctAnswerRadios.add(checkedRadioButton[j]);
} else {
wrongAnswersRadios.add(checkedRadioButton[j]);
}
}
}
});
j++;
}
}
linearLayout.addView(answerGroup[i]);
i++;
}

finishButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
for (int i = 0; i < answerGroup.length; i++) {
for (int j = 0; j < answer.length; j++) {
RadioButton correctRadio = correctAnswerRadios.get(j);
correctRadio.setTextColor(Color.GREEN);
RadioButton wrongRadio = wrongAnswersRadios.get(j);
wrongRadio.setTextColor(Color.RED);
answerGroup[i].getChildAt(j).setEnabled(false);
}
}
}
});

任何帮助将不胜感激。谢谢!

最佳答案

您需要初始化数组。例如:

checkedRadioButton = new RadioButton[size];

关于java - 如何在Java中为ArrayList中的所有元素设置文本颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33638487/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com