RecyclerView nullpointException

时间:2015-03-27 02:47:05

标签: android android-fragments android-recyclerview

每次尝试在片段内调用recyclerView时,我都会收到此零点异常。

正如您在下面的代码中所看到的,我已经声明了我的布局管理器。我尝试在recyclerViewlayoutManager内声明onViewCreatedonCreateView,但仍然是同样的错误。

这些片段位于viewPager内,然后每个片段中包含SwipeRefreshLayout。我有3个片段都包含recyclerView,如果我只使用一个错误没有显示。

private RecyclerView post;
private LinearLayoutManager mLayoutManager;
private SwipeRefreshLayout refreshLayout;

public NearByFragment(){

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_near_by, container, false);
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    post = (RecyclerView) getActivity().findViewById(R.id.lvPost);
    post.setHasFixedSize(true);
    setHasOptionsMenu(true);
    mLayoutManager = new LinearLayoutManager(getActivity());
    mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    post.setLayoutManager(mLayoutManager);
    post.setOnScrollListener(new ScrollListener());
    refreshLayout = (SwipeRefreshLayout) getActivity().findViewById(R.id.swipe_layout);
    refreshLayout.setColorSchemeColors(Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW);
    refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            refreshLayout.setRefreshing(false);
        }
    });
}

1 个答案:

答案 0 :(得分:3)

如果你的R.id.lvPost在R.layout.fragment_near_by中。你应该这样做:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_near_by, container, false);
    post = (RecyclerView) view.findViewById(R.id.lvPost);
    return view;
}