在片段中设置适配器

时间:2016-10-18 11:38:06

标签: android android-fragments gridview android-gridview

收到此错误:enter image description here 我试图在片段中显示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));
}

请在此纠正我。

3 个答案:

答案 0 :(得分:1)

  

评论return super并在结尾添加return view

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

答案 1 :(得分:0)

在设置适配器行

下面添加此行
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;
    }

答案 2 :(得分:-1)

在充气后返回视图

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