我在GridView Android中得到Null指针异常

时间:2014-09-20 06:21:34

标签: java android gridview

我使用Gridview在片段中获取空指针异常。 我的代码是

public class HomeFragment extends Fragment {
    GridView grid;
    String[] web = { "Bata", "Service", "puma", "Hush" };
    int[] imageId = { R.drawable.shoesmall, R.drawable.shoe1, R.drawable.shoe3,
            R.drawable.shoe4 };

    public HomeFragment(){}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

       View rootView = inflater.inflate(R.layout.fragment_home, container, false);
     //   ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_home, container);

        CustomGrid adapter = new CustomGrid(getActivity().getApplicationContext(), web, imageId);
        grid = (GridView) getView().findViewById(R.id.gridview);
        grid.setAdapter(adapter);
        grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                Toast.makeText(getActivity().getApplicationContext(),
                        "You Clicked at " + web[+position], Toast.LENGTH_SHORT)
                        .show();
            }
        });

        return rootView;
    }
}

任何人都可以指导为什么会这样吗?我不常用碎片。

1 个答案:

答案 0 :(得分:4)

您的getView()为空,因为尚未创建视图,因此请更改

 grid = (GridView) getView().findViewById(R.id.gridview);

 grid = (GridView) rootView.findViewById(R.id.gridview);