在Fragment中使用RecyclerView调用setLayoutManager报空对象引用崩溃
问题原因
你遇到的空指针异常由两个错误共同导致:
- 布局加载顺序错误:你在还未加载Fragment自身布局的前提下,就尝试查找RecyclerView控件,此时目标控件不存在
- 控件查找范围错误:你调用
getActivity().findViewById()从宿主Activity的布局树中查找控件,但RecyclerView定义在Fragment自己的fragment_dashboard.xml布局中,Activity布局里不存在对应id的控件,最终返回null,调用方法时触发空指针。
修复方案
修改Dashboard_Fragment类的onCreateView方法,先加载Fragment布局,再从布局中查找控件:
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // 先加载Fragment的根布局 View fragmentView = inflater.inflate(R.layout.fragment_dashboard, container, false); // 从当前Fragment的根布局中查找RecyclerView Recycler = fragmentView.findViewById(R.id.Recycler); layoutManager = new LinearLayoutManager(getActivity()); recyclerAdapter = new Dashboard_Recycler_Adapter(getActivity(), bookList); Recycler.setLayoutManager(layoutManager); Recycler.setAdapter(recyclerAdapter); // 返回加载完成的根布局 return fragmentView; }
额外注意事项
你当前的fragment_dashboard.xml中,id为textView2的TextView配置了android:layout_height="match_parent",会占满整个父布局遮挡下方的RecyclerView,建议修改为:
<TextView android:id="@+id/textView2" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="10dp" android:text="@string/dashboard_fragment" android:textSize="20sp" />
修改后RecyclerView即可正常显示内容。
内容的提问来源于stack exchange,提问作者Shrestha Nand
相关产品推荐
相关产品推荐

