java.lang.NullPointerException at android.support.v7.widget.RecyclerView.onMeasure

后端 未结 5 516
梦毁少年i
梦毁少年i 2020-12-06 04:20

I try to use RecyclerView with RecyclerView.Adapter but here is something wrong. I post my code below:

Layout:

   

        
5条回答
  •  时光说笑
    2020-12-06 05:18

    You have to set LayoutManager for RecycleView:

    Currently, android supports 3 kinds of layouts.

    If you want it seems a normal ListView, use LinearLayoutManager.

    If you want it seems a gridView, use GridLayoutManager.

    If you want it seem staggered, use StaggeredGridLayoutManager

    Constructors for 3 kinds layouts above

    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
    
    GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 2);
    
    StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(spanCount, StaggeredGridLayoutManager.HORIZONTAL);
    

    Then you set LinearLayout to RecycleView ( in this case I used LinearLayoutManager

    recyclerView = (RecyclerView) view.findViewById(R.id.saved_recycle_view);
    recyclerView.setHasFixedSize(true);
    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
    recyclerView.setLayoutManager(linearLayoutManager);
    

    Anyway, use OttoBus Library to pass out events from the Adapter to Activity/Fragment containing the RecycleView. Good luck !

提交回复
热议问题