gpt4 book ai didi

android - 将适配器分配给 Fragment 中的 GridView 时的空指针

转载 作者:行者123 更新时间:2023-11-29 21:30:42 27 4
gpt4 key购买 nike

将适配器分配给 Fragment 中的 View 时的空指针。

我有一个包含 fragment 的 Activity 。我想用 GridView 填充 fragment 。为此,我创建了一个自定义适配器 -

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;
}
}

我已经将 fragment 实现为 -

    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 异常。据我所知,它应该可以工作,因为我为适配器提供了适当的上下文(我也在调试时检查了它,该值不为空)。

提前致谢。

最佳答案

GridView mGridview = (GridView) getActivity().findViewById(R.id.gridView);

在上一行中将 getActivity() 更改为 rootView

关于android - 将适配器分配给 Fragment 中的 GridView 时的空指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19634769/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com