RecyclerView不显示内容且提示No adapter attached; skipping layout求助
问题排查与修复方案
错误原因
你出现No adapter attached; skipping layout错误的核心原因是:仅创建了ChartAdapter实例,但是没有调用RecyclerView.setAdapter()方法将Adapter和RecyclerView绑定,RecyclerView无法感知Adapter的存在,因此会跳过布局渲染流程,即便后续更新Adapter的数据也不会触发页面刷新。
修复方案
在你Fragment的onCreateView方法中,初始化Adapter和LayoutManager后,添加绑定Adapter的代码即可,修改后的对应代码片段如下:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment chartFragment = inflater.inflate(R.layout.fragment_chart, container, false); collatzViewModel = new ViewModelProvider(getActivity()).get(CollatzViewModel.class); mRecyclerView = (RecyclerView) chartFragment.findViewById(R.id.recycler_view_chart); mRecyclerView.setHasFixedSize(false); mLayoutManager = new LinearLayoutManager(getActivity()); mAdapter = new ChartAdapter(); mRecyclerView.setLayoutManager(mLayoutManager); // 新增这一行,绑定Adapter和RecyclerView mRecyclerView.setAdapter(mAdapter); collatzViewModel.getChartItems().observe(getViewLifecycleOwner(),(list)->{ mAdapter.setList(list); mAdapter.notifyDataSetChanged(); Log.v("list", "" + list.get(1).getSectionInformation()); }); return chartFragment; }
可选优化建议
- 可以将数据更新的通知逻辑封装到Adapter内部,避免外部漏写notify调用:
public void setList(ArrayList<ChartItem> list) { this.list = list; notifyDataSetChanged(); }
后续外部调用mAdapter.setList(list)即可,不需要再手动调用notifyDataSetChanged。
- 如果列表数据更新频繁、存在局部更新的场景,可以使用
DiffUtil代替全局notifyDataSetChanged,减少不必要的页面重绘,提升滑动流畅度。
内容的提问来源于stack exchange,提问作者Erick Sorto
相关产品推荐
相关产品推荐

