fix(android): resolve "Scrapped or attached views may not be recycled" crash #1046
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary
This PR fixes a frequent
java.lang.IllegalArgumentException: Scrapped or attached views may not be recycledcrash on Android.Motivation:
Users have reported crashes in production pointing to ViewPagerAdapter, specifically when views are being recycled or removed. This issue has been discussed in #1005.
The Fix:
The root cause was identified in the removeAll method of ViewPagerAdapter.kt. The previous implementation was manually removing the ViewHolder's container from the
RecyclerView(accessing it viachild.parent.parent). This manual manipulation violated theRecyclerViewcontract, causing its internal state ("Recycler") to desynchronize. It would believe a view was still attached or scrapped when it had been forcibly removed, leading to the crash during subsequent layout passes or recycling attempts.I updated removeAll to safely detach only the React Native child view from its immediate parent (the FrameLayout container). We then rely on
childrenViews.clear()andnotifyItemRangeRemoved, allowingRecyclerViewto handle the removal and recycling of its containers correctly.Fixes: #1005
Test Plan
I verified this fix by running an app that previously experienced this crash on Android.
What's required for testing (prerequisites)?
react-native-pager-view.What are the steps to reproduce (after prerequisites)?
childrenarray, specifically clearing the list (calling removeAll internally), while interacting with the pager (swiping).IllegalArgumentException.Compatibility
Checklist
README.md