使用DataBinding与ViewModel时RecyclerView触发IllegalStateException问题
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.xmlisn't using any setup that would force attachment to a parent (like incorrectmergeusage—thoughmergeis fine as long asattachToRootisfalse). - Timing of adapter setup: In your Fragment, call
setAdapter()insideonViewCreated()(notonCreate()) 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

