基本上,我在警报对话框中创建了一个 GridView。我像往常一样设置了一个数组适配器,它会按原样显示数组中的所有内容。然而稍后在代码中,我想突出显示 GridView 中的特定值,通过更改背景颜色,它会引发空指针异常。我知道它是哪一行,但是它应该包含孩子,但没有。
GridView 是这样创建的:
GridView g = new GridView(this);
final ArrayAdapter<String> Wordadapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.style,WordSearch);
String[] lag = WordSearch;
g.setId(2);
g.setBackgroundColor(getResources().getColor(android.R.color.black));
g.setHorizontalSpacing(-20);
g.setPadding(60,5, 10, 5);
g.setAdapter(Wordadapter);
g.setNumColumns(Length);
我试着像这样改变颜色
for(int j = StartPosition; j <= EndPos; j= j + Length) {
g = (GridView) findViewById(2);
g.getChildAt(j).setBackgroundColor(Color.BLUE);
}
for 循环中的行抛出空指针。当我检查 g 上的孩子时,即使数组中有 121 个元素,所有孩子 (12) 都是空的。
开始位置是 21,结束位置是 109,长度是 15,所以如果值有问题,它不会在第一次迭代时中断。
有任何想法吗?
额外代码:
AlertDialog.Builder aBuilder = new AlertDialog.Builder(this);
// set title
aBuilder.setTitle("The solution");
GridView g = new GridView(this);
final ArrayAdapter<String> Wordadapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.style,WordSearch);
String[] slag = WordSearch;
g.setId(1);
g.setBackgroundColor(getResources().getColor(android.R.color.black));
g.setHorizontalSpacing(-20);
g.setPadding(60,5, 10, 5);
g.setAdapter(Wordadapter);
g.setNumColumns(Length);
for(int i =0; i < Directions.length;i++) {
int EndPos;
int StartPosition = StartPos[i];
int Direction = Directions[i];
int Word = wordLengths[i];
EndPos = GetEndPosition(Direction,Word,StartPosition);
int difference = StartPosition - EndPos;
if ( Direction == 1)// direction down (1) {
difference = difference * -1;
if( difference % Length == 0) {
for(int j = StartPosition; j <= EndPos; j= j + Length) {
g = (GridView) Puzzle_Activity.this.findViewById(2);
g.getChildAt(j).setBackgroundColor(Color.BLUE);
}
}
}
}