我正在尝试将文本颜色设置为红色,以及所有单选按钮,但是来自我拥有的所有广播组。何时使用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);
}
}
}
});
谢谢!
答案 0 :(得分:1)
<强>更新强>
试试这段代码:
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);
}
}
}
});
答案 1 :(得分:0)
试试这个:
finishButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
for (int i = 0; i < 4; i++) {
radioGroup[i].clearCheck();
for (int j = 0; j < 4; j++) {
radioGroup[i].getChildAt(j).setEnabled(true);
((RadioButton)radioGroup[i].getChildAt(j)).setTextColor(Color.RED);
((RadioButton)radioGroup[i].getChildAt(j)).setChecked(false);
}
}
}
});
答案 2 :(得分:-1)
我很棒!
你只想获得4 RadioGroup
和4 RadioButton
?
将for(b: bs )
更改为for(int i = 0;i<bs.size();i++)
finishButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try{
for (int i = 0; i < radioGroup.length; i++) {
int len = radioGroup[i].getChildCount();
for (int j = 0; j < len; j++) {
radioGroup[i].getChildAt(j).setBackgroundColor(
Color.GREEN);
}
}
}catch(Throwable e){
}
}
});