我正在尝试将文本颜色设置为红色,设置为所有单选按钮但我拥有的所有单选按钮的颜色。使用answer[i].setTextColor(Color.RED);
时,仅适用于最后一个无线电组。
如果尝试使用radioGroup[i].getChildAt(j).setBackgroundColor(Color.GREEN);
更改所有单选按钮的背景色,则会出现以下错误:Attempt to invoke virtual method 'android.view.View android.widget.RadioGroup.getChildAt(int)' on a null object reference
。
我怎样才能解决这个问题?还有其他方法可以做到吗?
这是我的代码:
radioGroup = new RadioGroup[4];
answer = new RadioButton[4];
for (Question qn : questions) {
int i = 0;
radioGroup[i] = new RadioGroup(this);
radioGroup[i].setOrientation(RadioGroup.VERTICAL);
int j = 0;
for (Answer an : answers) {
if (qn.getID() == an.getQuestion_id_answer()) {
String answers_log = " " + an.getAnswer();
answer[j] = new RadioButton(this);
answer[j].setText(answers_log);
radioGroup[i].addView(answer[j]);
j++;
}
}
linearLayout.addView(radioGroup[i]);
i++;
}
finishButton = new Button(this);
linearLayout.addView(finishButton);
finishButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
for (int i = 0; i < radioGroup.length; i++) {
for (int j = 0; j < answer.length; j++) {
answer[i].setTextColor(Color.RED);
}
}
}
});
谢谢!
最佳答案
更新
试试这个代码:
radioGroup = new RadioGroup[4];
answer = new RadioButton[4];
int i = 0;
for (Question qn : questions) {
radioGroup[i] = new RadioGroup(this);
radioGroup[i].setOrientation(RadioGroup.VERTICAL);
int j = 0;
for (Answer an : answers) {
if (qn.getID() == an.getQuestion_id_answer()) {
String answers_log = " " + an.getAnswer();
answer[j] = new RadioButton(this);
answer[j].setText(answers_log);
radioGroup[i].addView(answer[j]);
j++;
}
}
linearLayout.addView(radioGroup[i]);
i++;
}
finishButton = new Button(this);
linearLayout.addView(finishButton);
finishButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
for (int i = 0; i < radioGroup.length; i++) {
for (int j = 0; j < radioGroup[i].getChildCount(); j++) {
radioGroup[i].getChildAt(j).setBackgroundColor(Color.GREEN);
}
}
}
});