所以我在这里有这些代码,它运行时不会崩溃。但是,当我将“ this”传递给gridadapter时,mContext为null。我试图通过getApplicationContext(),但是仍然无法使getImage方法正常运行,因为Context为null,因此getResources.getIdentifier行不返回任何内容。如果有人可以教我这是怎么回事以及如何解决它,我对此表示赞赏。谢谢。
public class ChampionInfo extends FragmentActivity {
GridView gridtable;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_champion_info);
gridtable = (GridView) findViewById(R.id.gridtable);
gridtable.setAdapter(new GridAdapter(getApplicationContext()));
}
public class GridAdapter extends BaseAdapter {
private Context mContext;
String[] list = getResources().getStringArray(R.array.championlist);
int[] champImage = getImage();
public int[] getImage() {
int[] tempImage = new int[list.length];
for (int i = 0; i < list.length; i++) {
tempImage[i] = getResources().getIdentifier(list[i],
"drawable", getPackageName());
}
return tempImage;
}
// Constructor
public GridAdapter(Context c) {
mContext = c;
}
public int getCount() {
return champImage.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(champImage[position]);
return imageView;
}
// Keep all Images in array
}
}
最佳答案
问题的根源在于您尝试使用以下命令内联初始化成员变量
int[] champImage = getImage();
这在将
mContext
设置为有效值的构造函数之前执行。但是,在mContext
调用中null
是getImage()
的事实应该是无关紧要的,因为您实际上从未在该方法中使用mContext
。总体问题是,您需要注意执行顺序。