我在Android中遇到了GridView的问题。我看过类似的帖子,但这不一样。问题是我为我的GridView设置了一个适配器然后我想做一些计算并决定选择GridView的一个元素,我想将TextView的背景设置为绿色。 这是代码示例:
GridView gv = findViewById(R.id.gridView);
final String[] answerStrings = new String[] {
TEXT_IN_DRAG_AND_DROP_BOXES, TEXT_IN_DRAG_AND_DROP_BOXES,
TEXT_IN_DRAG_AND_DROP_BOXES };
ArrayAdapter<String> answersViewAdapter = new ArrayAdapter<String>(
this, android.R.layout.simple_list_item_1, answerStrings);
gv.setAdapter(answersViewAdapter);
int a = // some process which tells me which child should I change the background of
gv.getChildAt(a-1).setBackgroundColor(
DRAG_AND_DROP_COLOR_BACKGROUND);
我收到了NPE,我知道这是因为视图还不可见。但我不知道该如何解决这个问题。
答案 0 :(得分:0)
创建自定义适配器并在getView中执行此计算以确定textview以更改背景颜色。
试试这个:
ArrayAdapter<String> choicesForViewAdapter = new ArrayAdapter<String>(
this, R.layout.simple_list_item_1, choices) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = super.getView(position, convertView, parent);
int temp = userAnswers[questionNumber - 1];
while (temp != 0) {
int a = temp % 10;
if (position == a - 1) {
v.setBackgroundColor(DRAG_AND_DROP_COLOR_BACKGROUND);
break;
}
temp = temp / 10;
}
return v;
};
};