【发布时间】:2012-03-09 04:04:53
【问题描述】:
我想在我的活动中显示画廊视图,但我不知道它发生了什么,它没有显示任何内容并崩溃。
在创建活动方法时,我有:
// initializing gallery view with predefined images
gallery = (Gallery) findViewById(R.id.gallery);
gallery.setAdapter(new ImageAdapter(this));
gallery.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Toast.makeText(NewsList.this, "" + position, Toast.LENGTH_SHORT).show();
}
});
然后在单独的 java 文件中,我有如下的图像适配器: 公共类 ImageAdapter 扩展 BaseAdapter {
int mGalleryItemBackground;
private Context mContext;
private Integer[] mImageIds = {
R.drawable.g_adira,
R.drawable.g_akim,
R.drawable.g_alyah,
R.drawable.g_atilia,
R.drawable.g_awi,
R.drawable.g_estrange,
R.drawable.g_hafiz,
R.drawable.g_hazama,
R.drawable.g_jac,
R.drawable.g_kristal,
R.drawable.g_shila,
R.drawable.g_stacy
};
public ImageAdapter(Context c) {
mContext = c;
TypedArray attr = mContext.obtainStyledAttributes(R.styleable.HelloGallery);
mGalleryItemBackground = attr.getResourceId(R.styleable.HelloGallery_android_galleryItemBackground, 0);
attr.recycle();
Log.i("ImageAdapter", "Gallery setupped successfully.");
}
public int getCount() {
return mImageIds.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
imageView.setImageResource(mImageIds[position]);
imageView.setLayoutParams(new Gallery.LayoutParams(150, 120));
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setBackgroundResource(mGalleryItemBackground);
Log.i("ImageAdapter", "Position:" + position);
return imageView;
}
}
画廊的XML代码:
<?xml version="1.0" encoding="utf-8"?>
<Gallery
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gallery"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true" />
我不知道为什么它不起作用。在 logcat 中,我看到我的日志放在构造函数中,因为我得到空指针异常,并且引用的是“gallery.setAdapter(new ImageAdapter(this));”
任何建议表示赞赏。谢谢
【问题讨论】: