将RecyclerView添加到Fragment时出现NullPointerException

时间:2016-03-24 03:46:43

标签: android android-fragments android-recyclerview android-inflate

在我的片段onCreateView方法中,我正在给包含RecyclerView的布局进行充气。但是,当我尝试引用该视图时,我在以下行得到NullPointerException:

mRecyclerView.setLayoutManager(mStaggeredLayoutManager);

我做错了什么?

这是我的代码:

public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstance){
        final StaggeredGridLayoutManager mStaggeredLayoutManager = new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL);

        mRecyclerView = (RecyclerView)getActivity().findViewById(R.id.list);
        mRecyclerView.setLayoutManager(mStaggeredLayoutManager);

        mRecyclerView.setHasFixedSize(true); //Data size is fixed - improves performance
        mAdapter = new TravelListAdapter(getActivity());
        mRecyclerView.setAdapter(mAdapter);
        return inflater.inflate(R.layout.start_fragment,container,false);
}

2 个答案:

答案 0 :(得分:2)

你正在做getActivity.findViewById(),这是行不通的。您刚刚创建了视图,但它尚未附加到活动。为此,您必须在片段视图中找到视图,而不是活动视图。

首先,膨胀片段的视图,然后执行inflatedView.findViewById(R.id.list)

示例:

public View onCreateView(...){
    View inflatedView = inflater.inflate(R.layout.start_fragment, container, false);

    mRecyclerView = (RecyclerView) inflatedView.findViewById(R.id.list);

    return inflatedView;
}

答案 1 :(得分:0)

        @Override
        public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        final StaggeredGridLayoutManager mStaggeredLayoutManager = new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL);
mRecyclerView = (RecyclerView) view.findViewById(R.id.list);
mRecyclerView.setLayoutManager(mStaggeredLayoutManager);
mRecyclerView.setHasFixedSize(true);
mAdapter = new TravelListAdapter(getActivity());
mRecyclerView.setAdapter(mAdapter);
super.onViewCreated(view, savedInstanceState);

        }

这就是我要做的事情