0

我有一个小问题。我正在尝试使用片段创建布局,但是当我调用 setAdapter 方法时,我有一个 Java NullPointerException,我找不到错误。谢谢大家!

public static class DemoObjectFragment extends Fragment {

        public static final String ARG_OBJECT = "object";
        private List<RowItem> rowItems;

        private static Integer[] images = {
            R.drawable.red,
            R.drawable.red,
            R.drawable.red,
            R.drawable.red,
            R.drawable.red,
            R.drawable.red,
            R.drawable.red,            
            R.drawable.red
            };

        ListView lv;

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_collection_object, container, false);
            Bundle args = getArguments();

            lv = (ListView) this.getActivity().findViewById(R.id.myList);
            rowItems = new ArrayList<RowItem>();

            String[] titles = {"Movie1","Movie2","Movie3","Movie4","Movie5","Movie6","Movie7","Movie8"};
            String[] descriptions = {"First Movie","Second movie","Third Movie","Fourth Movie","Fifth Movie",
                    "Sixth Movie","Seventh Movie","Eighth Movie"};
            //Populate the List
            for (int i = 0; i < titles.length; i++) {
                RowItem item = new RowItem(images[i], titles[i], descriptions[i]);
                rowItems.add(item);
            }

            // Set the adapter on the ListView
            LazyAdapter adapter = new LazyAdapter(getActivity(), R.layout.list_row, rowItems);
            lv.setAdapter(adapter);

            lv.setOnItemSelectedListener(new OnItemSelectedListener() {

                @Override
                public void onItemSelected(AdapterView<?> arg0, View arg1,
                        int arg2, long arg3) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onNothingSelected(AdapterView<?> arg0) {
                    // TODO Auto-generated method stub

                }
            });

            //((TextView) rootView.findViewById(android.R.id.text1)).setText(Integer.toString(args.getInt(ARG_OBJECT)));
            return rootView;
        }
    }
4

1 回答 1

9

改变

lv = (ListView) this.getActivity().findViewById(R.id.myList);

lv = (ListView) rootView.findViewById(R.id.myList);

您正在寻找 Activity 中的 ListView,但它可能属于片段的视图层次结构(它在里面声明R.layout.fragment_collection_object

于 2014-02-25T09:22:21.607 回答