只需在GridView上设置适配器即可进行简单的练习:
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(this));
ImageAdapter是另一个类,如下所示:
public class ImageAdapter extends BaseAdapter {
// ---the images to display---
public Integer[] imageIDs = { R.drawable.one, R.drawable.two,
R.drawable.three, R.drawable.four, R.drawable.five,
R.drawable.six };
private Context context;
public ImageAdapter(Context c) {
context = c;
}
// ---returns the number of images---
public int getCount() {
return imageIDs.length;
}
// ---returns the ID of an item---
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
// ---returns an ImageView view---
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(context);
imageView.setLayoutParams(new GridView.LayoutParams(185, 200));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(5, 20, 5, 5);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(imageIDs[position]);
return imageView;
}
}
当我调试代码时,app会在gridview.setAdapter行崩溃,并在 this 上报告 java.lang.NullPointerException 。有什么想法可以解决这个问题吗?
答案 0 :(得分:3)
我认为你的问题不是this
为空,这没有意义,但gridView
为空。
通常是因为:
setContentView()
之前致电findViewById
。findViewById
。答案 1 :(得分:0)
这可能会有所帮助:
Context context = getApplicationContext();
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(context));
答案 2 :(得分:0)
使用
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(ClassName.this));
其中ClassName是类名,并扩展了Android Activity。