Remove views from their parent on recycle (#49851)

Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/49851

Android doesn't allow to mount a view that already has a parent. View recycling removes all children from a view. But if some views don't support recycling, they'll keep a reference to their children. Children being recycled will cause an exception when being mounted.

This diff removes the view from its parent when it is being recycled. This guarantees that whatever the parent, the view can be mounted after being recycled.

bypass-github-export-checks

Changelog: [Internal]

Reviewed By: sammy-SC

Differential Revision: D70672120

fbshipit-source-id: 023d8fb48982d6d9ae7f9c537f7f2bb21cf15066
This commit is contained in:
Nick Lefever
2025-03-06 08:34:02 -08:00
committed by Facebook GitHub Bot
parent a51fa6c002
commit 1114f4c35a
2 changed files with 12 additions and 0 deletions
@@ -111,6 +111,12 @@ public class ReactTextView extends AppCompatTextView implements ReactCompoundVie
// Set default field values
initView();
// If the view is still attached to a parent, we need to remove it from the parent
// before we can recycle it.
if (getParent() != null) {
((ViewGroup) getParent()).removeView(this);
}
BackgroundStyleApplicator.reset(this);
// Defaults for these fields:
@@ -193,6 +193,12 @@ public class ReactViewGroup extends ViewGroup
// Remove any children
removeAllViews();
// If the view is still attached to a parent, we need to remove it from the parent
// before we can recycle it.
if (getParent() != null) {
((ViewGroup) getParent()).removeView(this);
}
// Reset background, borders
updateBackgroundDrawable(null);