From 1114f4c35a95ae583dd45dd27d2f10f246097db4 Mon Sep 17 00:00:00 2001 From: Nick Lefever Date: Thu, 6 Mar 2025 08:34:02 -0800 Subject: [PATCH] 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 --- .../java/com/facebook/react/views/text/ReactTextView.java | 6 ++++++ .../java/com/facebook/react/views/view/ReactViewGroup.java | 6 ++++++ 2 files changed, 12 insertions(+) diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTextView.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTextView.java index cd2b25044bd..d1e4b4eb10e 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTextView.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTextView.java @@ -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: diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewGroup.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewGroup.java index da20629d4fa..65349b852e2 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewGroup.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewGroup.java @@ -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);