在片段中设置适配器

set adapter in fragment

出现此错误: 我试图在片段中显示 gridview,但在设置适配器时发生此错误。

我的片段是这样的:

public class ExploreFragment extends Fragment {


GridView gv;
Context context;
ArrayList prgmName;
public static String [] prgmNameList={"Adventure","Animals","Automotive","Foods","Diy","Business","Technology","Creative Art","Entertainment"};
public static int [] prgmImages={R.drawable.adventure,R.drawable.animals,R.drawable.automobiles,R.drawable.food_and_drinks,R.drawable.diy,R.drawable.business,R.drawable.technology,R.drawable.creativity,R.drawable.entertainment};

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    return super.onCreateView(inflater, container, savedInstanceState);
    View view = inflater.inflate(R.layout.fragment_explore,container,false);
    gv=(GridView) view.findViewById(R.id.fragment_explore_gridView1);
    gv.setAdapter(new CustomAdapter((MainActivity) getContext().getApplicationContext(),prgmNameList,prgmImages));
}

这里请指正。

Comment return super and add return view at end

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
       // return super.onCreateView(inflater, container, savedInstanceState);
        View view = inflater.inflate(R.layout.fragment_explore,container,false);
        gv=(GridView) view.findViewById(R.id.fragment_explore_gridView1);
        gv.setAdapter(new CustomAdapter((MainActivity) getContext().getApplicationContext(),prgmNameList,prgmImages));
        return view;
    }

在设置适配器行下方添加此行

return view;

您的 onCreateView 将如下所示:

public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_explore,container,false);
        gv=(GridView) view.findViewById(R.id.fragment_explore_gridView1);
        gv.setAdapter(new CustomAdapter((MainActivity) getContext().getApplicationContext(),prgmNameList,prgmImages));
        return view;
    }

return充气后的样子

 @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
       // return super.onCreateView(inflater, container, savedInstanceState);
        View view = inflater.inflate(R.layout.fragment_explore,container,false);
        gv=(GridView) view.findViewById(R.id.fragment_explore_gridView1);
        gv.setAdapter(new CustomAdapter((MainActivity) getContext().getApplicationContext(),prgmNameList,prgmImages));
        return view;
    }