Fragment中使用RecyclerView遇双错误:Adapter上下文不兼容+空指针异常
解决Fragment中RecyclerView的两个常见问题
我来帮你搞定这两个坑,都是Fragment结合RecyclerView开发时很容易踩的点:
问题1:LayoutInflater.from(context)类型不匹配报错
问题原因
你的SongCardAdapter里把上下文对象定义成了LibraryFragment类型,但LayoutInflater.from()需要的是标准的android.content.Context实例——Fragment本身并不是Context,它只是依附于Activity的组件,直接传Fragment对象会导致类型不兼容。
修复方案
- 把Adapter里的上下文字段改成
Context类型; - 创建Adapter时,传入Fragment的
requireContext()(比getActivity()更安全,能避免Activity为空的异常情况)。
修改后的SongCardAdapter关键代码:
public class SongCardAdapter extends RecyclerView.Adapter<SongCardAdapter.viewHolder> { private ArrayList<SongCardModel> list; private Context context; // 将类型改为Context public SongCardAdapter(ArrayList<SongCardModel> list, Context context) { this.list = list; this.context = context; } @NonNull @Override public viewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { // 此处不再报错 View view = LayoutInflater.from(context).inflate(R.layout.libray_recycler_view_layout, parent, false); return new viewHolder(view); } // 其余代码保持不变... }
问题2:NullPointerException(调用null对象的findViewById)
问题原因
你在onCreateView里的逻辑顺序完全错了:在libraryRecyclerView还没初始化(还是null)的时候,就调用了libraryRecyclerView.findViewById(),这必然会触发空指针异常。正确的流程应该是先加载Fragment的布局得到根View,再从根View中查找RecyclerView。
另外还要注意:你原来的代码里没有给RecyclerView设置LayoutManager,即使修复了空指针,RecyclerView也不会显示任何内容,这是另一个容易遗漏的点。
修复方案
修改后的LibraryFragment代码:
public class LibraryFragment extends Fragment { private RecyclerView libraryRecyclerView; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // 第一步:先加载Fragment的布局,得到根View View rootView = inflater.inflate(R.layout.library_fragment, container, false); // 第二步:从根View中查找RecyclerView libraryRecyclerView = rootView.findViewById(R.id.library_recyclerview); // 准备数据 ArrayList<SongCardModel> list = new ArrayList<>(); list.add(new SongCardModel(R.drawable.roses_cover, "Roses")); list.add(new SongCardModel(R.drawable.roses_cover, "Roses")); list.add(new SongCardModel(R.drawable.roses_cover, "Roses")); // ... 其余数据添加 // 第三步:创建Adapter并关联RecyclerView SongCardAdapter adapter = new SongCardAdapter(list, requireContext()); libraryRecyclerView.setAdapter(adapter); // 必须添加:给RecyclerView设置布局管理器,否则不会显示内容 libraryRecyclerView.setLayoutManager(new LinearLayoutManager(requireContext())); // 返回根View return rootView; } }
最后额外检查:你Adapter里的布局文件名是libray_recycler_view_layout,注意拼写是否正确(library少了一个字母r?如果是笔误请修正,否则会找不到布局文件)。
内容的提问来源于stack exchange,提问作者Alex Ed
相关产品推荐
相关产品推荐

