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

使用DataBinding与ViewModel时RecyclerView触发IllegalStateException问题

Fixing "ViewHolder views must not be attached when created" with DataBinding in RecyclerView

Let's break down how to fix this crash and understand why it's happening.

Why This Crash Happens

The core issue here is that RecyclerView expects your ViewHolder's item view to not be attached to any parent layout when the ViewHolder is created. If you pass true to the attachToRoot parameter during inflation, the view gets immediately attached to the parent (your RecyclerView's container), which violates RecyclerView's internal rules and triggers this exception.

The Fix for DataBinding

Even though your code looks like it's using false for attachToRoot, let's adjust the onCreateViewHolder method to follow the safest practice for RecyclerView + DataBinding:

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): OtherVideoCategoriesRecyclerAdapter.ViewHolder {
    // Use parent's context instead of the passed-in context for more reliability
    val inflater = LayoutInflater.from(parent.context)
    // Explicitly set attachToRoot to false - this is critical!
    val binding = ItemOtherVideoCategoryBinding.inflate(inflater, parent, false)
    return ViewHolder(binding)
}

Additional Checks to Ensure Stability

  • Verify your layout file: Make sure the root of your item_other_video_category.xml isn't using any setup that would force attachment to a parent (like incorrect merge usage—though merge is fine as long as attachToRoot is false).
  • Timing of adapter setup: In your Fragment, call setAdapter() inside onViewCreated() (not onCreate()) to ensure the RecyclerView is fully initialized before you attach the adapter.
  • Adapter singleton in ViewModel: Your getAdapter() method already handles singleton initialization correctly, so that part should be okay—just ensure you're not accidentally creating multiple adapter instances elsewhere.

Why This Works

By setting attachToRoot = false, we tell DataBinding to inflate the layout's view hierarchy without immediately attaching it to the parent ViewGroup. RecyclerView will handle attaching the view to its container at the appropriate time (when the item needs to be displayed on screen), which aligns perfectly with its internal lifecycle rules.

内容的提问来源于stack exchange,提问作者Vivek Mishra

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 05:37:13