将适配器分配给片段中的视图时出现空指针。
我有一个包含片段的活动。我想用 GridView 填充片段。为此,我创建了一个自定义适配器 -
public class MyBaseAdapter extends BaseAdapter {
private Context mContext;
private List<ResolveInfo> mAppList;
MyBaseAdapter(Context c, List<ResolveInfo> l) {
mContext = c;
mAppList = l;
}
public int getCount() {
return mAppList.size();
}
public Object getItem(int position) {
return mAppList.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
// if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(200, 200));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
ResolveInfo resolveInfo = mAppList.get(position);
imageView.setImageDrawable(resolveInfo
.loadIcon(mPackageManager));
return imageView;
}
}
我已将片段实现为-
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.grid_of_app, container, false);
HashMap<String, String> pkClsPair = new HashMap<String, String>();
pkClsPair.put("com.android.contacts", "com.android.contacts.activities.PeopleActivity");
pkClsPair.put("com.android.gallery", "com.android.camera.GalleryPicker");
mPackageManager = getActivity().getPackageManager();
List<ResolveInfo> intentList = null, intentList_temp = null;
Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
for (Map.Entry<String, String> entry : pkClsPair.entrySet()) {
intent.setClassName(entry.getKey(), entry.getValue());
if (intentList == null)
intentList = getActivity().getPackageManager().queryIntentActivities(intent, 0);
else {
intentList_temp = (getActivity().getPackageManager().queryIntentActivities(intent, 0));
intentList.addAll(intentList_temp);
}
}
mBaseAdapter = new MyBaseAdapter(getActivity(), intentList);
GridView mGridview = (GridView) getActivity().findViewById(R.id.gridView);
mGridview.setAdapter(mBaseAdapter);
mGridview.setOnItemClickListener(mOnItemClickListener);
return rootView;
}
但是,在将适配器 - mBaseAdapter - 分配给 Gridview 时,我似乎遇到了 NullPointer 异常。据我所知,它应该可以工作,因为我为适配器提供了适当的上下文(我也在调试时检查了它,该值不为空)。
提前致谢。