You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

RecyclerView无适配器绑定报错求助,附Home Fragment代码

解决E/RecyclerView: No adapter attached; skipping layout报错

先修复HomeFragment的视图绑定错误

你当前的onCreateView方法存在核心问题:你通过FragmentHomeBinding.inflate创建了绑定实例,但返回的是super.onCreateView的结果,这会导致后续操作的binding对应的视图根本没被加载到Fragment中,子Fragment可能无法正常初始化,进而引发连锁问题。

修改方式二选一:

方式1:在onCreateView中返回binding.root

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View {
    binding = FragmentHomeBinding.inflate(inflater, container, false)
    return binding.root
}

方式2:利用Fragment构造函数传入的布局,在onViewCreated中绑定视图

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    // 用bind替代inflate,绑定已加载的视图
    binding = FragmentHomeBinding.bind(view)
    // 后续的ViewPager2初始化代码保持不变
}

排查子Fragment的RecyclerView配置

报错的核心是RecyclerView未绑定Adapter就开始渲染,这个RecyclerView应该来自你的子Fragment(MainCategoryFragment或PersonalProtectionEquipmentsFragment),需要检查以下几点:

  • 确保RecyclerView实例通过View Binding或findViewById正确获取,没有ID拼写错误
  • 必须在RecyclerView渲染前(推荐在onViewCreated方法中)完成Adapter和LayoutManager的设置,即使初始数据为空
  • 如果有异步加载数据的逻辑,先初始化空Adapter绑定到RecyclerView,等数据加载完成后再更新Adapter的数据源

示例子Fragment正确写法:

class MainCategoryFragment : Fragment(R.layout.fragment_main_category) {
    private lateinit var binding: FragmentMainCategoryBinding
    private lateinit var recyclerAdapter: YourCustomAdapter

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding = FragmentMainCategoryBinding.bind(view)
        
        // 先初始化空Adapter并绑定
        recyclerAdapter = YourCustomAdapter(arrayListOf())
        binding.recyclerView.adapter = recyclerAdapter
        // 必须设置LayoutManager,否则RecyclerView无法正常工作
        binding.recyclerView.layoutManager = LinearLayoutManager(requireContext())
        
        // 异步加载数据并更新Adapter
        loadCategoryData()
    }

    private fun loadCategoryData() {
        // 示例:通过ViewModel观察数据变化
        yourViewModel.categoryData.observe(viewLifecycleOwner) { dataList ->
            recyclerAdapter.updateData(dataList)
        }
    }
}

额外注意事项

  • 不要在onCreate方法中操作RecyclerView,此时视图还未完成初始化
  • 确保RecyclerView的LayoutManager已设置(LinearLayoutManager/GridLayoutManager等),缺少LayoutManager也会导致渲染异常
  • 如果使用View Binding,确认布局文件中的RecyclerView ID与代码中引用的一致

内容的提问来源于stack exchange,提问作者Mustafa Mohamed Ahmed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 10:42:37