[java] The specified child already has a parent. You must call removeView() on the child's parent first (Android)

I have to switch between two layouts frequently. The error is happening in the layout posted below.

When my layout is called the first time, there doesn't occur any error and everything's fine. When I then call a different layout (a blank one) and afterwards call my layout a second time, it throws the following error:

> FATAL EXCEPTION: main
>     java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

My layout-code looks like this:

    tv = new TextView(getApplicationContext()); // are initialized somewhere else
    et = new EditText(getApplicationContext()); // in the code


private void ConsoleWindow(){
        runOnUiThread(new Runnable(){

     @Override
     public void run(){

        // MY LAYOUT:
        setContentView(R.layout.activity_console);
        // LINEAR LAYOUT
        LinearLayout layout=new LinearLayout(getApplicationContext());
        layout.setOrientation(LinearLayout.VERTICAL);
        setContentView(layout);

        // TEXTVIEW
        layout.addView(tv); //  <==========  ERROR IN THIS LINE DURING 2ND RUN
        // EDITTEXT
        et.setHint("Enter Command");
        layout.addView(et);
        }
    }
}

I know this question has been asked before, but it didn't help in my case.

This question is related to java android android-edittext textview parent-child

The answer is


If in your XML you have layout with id "root" It`s problem, just change id name


My case was different the child view already had a parent view i am adding the child view inside parent view to different parent. example code below

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/lineGap"
>
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="@color/black1"
    android:layout_gravity="center"
    android:gravity="center"
    />

</LinearLayout>

And i was inflating this view and adding to another LinearLayout, then i removed the LinaarLayout from the above layout and its started working

below code fixed the issue:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:gravity="center"
   android:textColor="@color/black1" />

It happened with me when I was using Databinding for Activity and Fragments.

For fragment - in onCreateView we can inflate the layout in traditional way using inflater. and in onViewCreated method, binding object can be updated as

 binding = DataBindingUtil.getBinding<FragmentReceiverBinding>(view) as FragmentReceiverBinding

It solved my issue


I came here on searching the error with my recyclerview but the solution didn't work (obviously). I have written the cause and the solution for it in case of recyclerview. Hope it helps someone.

The error is caused if in the onCreateViewHolder() the following method is followed:

layoutInflater = LayoutInflater.from(context);
return new VH(layoutInflater.inflate(R.layout.single_row, parent));

Instead it should be

return new VH(layoutInflater.inflate(R.layout.single_row, null));

simply pass the argument

attachtoroot = false

View view = inflater.inflate(R.layout.child_layout_to_merge, parent_layout, false);

I got this message while trying to commit a fragment using attach to root to true instead of false, like so:

return inflater.inflate(R.layout.fragment_profile, container, true)

After doing:

return inflater.inflate(R.layout.fragment_profile, container, false)

It worked.


I was facing the same error, and look what I was doing. My bad, I was trying to add the same view NativeAdView to the multiple FrameLayouts, resolved by creating a separate view NativeAdView for each FrameLayout, Thanks


In my case it happens when i want add view by parent to other view

View root = inflater.inflate(R.layout.single, null);
LinearLayout lyt = root.findViewById(R.id.lytRoot);
lytAll.addView(lyt);  // ->  crash

you must add parent view like this

View root = inflater.inflate(R.layout.single, null);
LinearLayout lyt = root.findViewById(R.id.lytRoot);
lytAll.addView(root);

In my case the problem was caused by the fact that I was inflating parent View with <merge> layout. In this case, addView() caused the crash.

View to_add = inflater.inflate(R.layout.child_layout_to_merge, parent_layout, true);
// parent_layout.addView(to_add); // THIS CAUSED THE CRASH

Removing addView() helped to solve the problem.


If other solution is not working like:

View view = inflater.inflate(R.layout.child_layout_to_merge, parent_layout, false);

check for what are you returning from onCreateView of fragment is it single view or viewgroup? in my case I had viewpager on root of xml of fragment and I was returning viewpager, when i added viewgroup in layout i didnt updated that i have to return viewgroup now, not viewpager(view).


I found another fix:

if (mView.getParent() == null) {
                    myDialog = new Dialog(MainActivity.this);
                    myDialog.setContentView(mView);
                    createAlgorithmDialog();
                } else {
                    createAlgorithmDialog();
                }

Here i just have an if statement check if the view had a parent and if it didn't Create the new dialog, set the contentView and show the dialog in my "createAlgorithmDialog()" method.

This also sets the positive and negative buttons (ok and cancel buttons) up with onClickListeners.


My error was define the view like this:

view = inflater.inflate(R.layout.qr_fragment, container);

It was missing:

view = inflater.inflate(R.layout.qr_fragment, container, false);

frameLayout.addView(bannerAdView); <----- if you get error on this line the do like below..

if (bannerAdView.getParent() != null)

  ((ViewGroup) bannerAdView.getParent()).removeView(bannerAdView);

   frameLayout.addView(bannerAdView);     <------ now added view

My problem is related to many of the other answers, but a little bit different reason for needing to make the change... I was trying to convert an Activity to a Fragment. So I moved the inflate code from onCreate to onCreateView, but I forgot to convert from setContentView to the inflate method, and the same IllegalStateException brought me to this page.

I changed this:

binding = DataBindingUtil.setContentView(requireActivity(), R.layout.my_fragment)

to this:

binding = DataBindingUtil.inflate(inflater, R.layout.my_fragment, container, false)

That solved the problem.


You must first remove the child view from its parent.

If your project is in Kotlin, your solution will look slightly different than Java. Kotlin simplifies casting with as?, returning null if left side is null or cast fails.

(childView.parent as? ViewGroup)?.removeView(childView)
newParent.addView(childView)

Kotlin Extension Solution

If you need to do this more than once, add this extension to make your code more readable.

childView.removeSelf()

fun View?.removeSelf() {
    this ?: return
    val parentView = parent as? ViewGroup ?: return
    parentView.removeView(this)
}

It will safely do nothing if this View is null, parent view is null, or parent view is not a ViewGroup


In my case, I was doing this (wrong):

...
TextView content = new TextView(context);
for (Quote quote : favQuotes) {
  content.setText(quote.content);
...

instead of (good):

...
for (Quote quote : favQuotes) {
  TextView content = new TextView(context);
  content.setText(quote.content);
...

The code below solved it for me:

@Override
public void onDestroyView() {
    if (getView() != null) {
        ViewGroup parent = (ViewGroup) getView().getParent();
        parent.removeAllViews();
    }
    super.onDestroyView();
}

Note: The error was from my fragment class and by overriding the onDestroy method like this, I could solve it.


if(tv!= null){
    ((ViewGroup)tv.getParent()).removeView(tv); // <- fix
}

You can use this methode to check if a view has children or not .

public static boolean hasChildren(ViewGroup viewGroup) {
    return viewGroup.getChildCount() > 0;
 }

check if you already added the view

if (textView.getParent() == null)
    layout.addView(textView);

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to android-edittext

This view is not constrained vertically. At runtime it will jump to the left unless you add a vertical constraint Design Android EditText to show error message as described by google Change EditText hint color when using TextInputLayout How to change the floating label color of TextInputLayout The specified child already has a parent. You must call removeView() on the child's parent first (Android) Edittext change border color with shape.xml Changing EditText bottom line color with appcompat v7 Soft keyboard open and close listener in an activity in Android EditText underline below text property Custom designing EditText

Examples related to textview

Kotlin: How to get and set a text to TextView in Android using Kotlin? How to set a ripple effect on textview or imageview on Android? The specified child already has a parent. You must call removeView() on the child's parent first (Android) Android: Creating a Circular TextView? android on Text Change Listener Android - Set text to TextView Placing a textview on top of imageview in android Rounded corner for textview in android Different font size of strings in the same TextView Auto-fit TextView for Android

Examples related to parent-child

The specified child already has a parent. You must call removeView() on the child's parent first (Android) Example of waitpid() in use? get parent's view from a layout CSS :: child set to change color on parent hover, but changes also when hovered itself How to pass data from 2nd activity to 1st activity when pressed back? - android Make absolute positioned div expand parent div height JavaScript DOM: Find Element Index In Container How to set opacity in parent div and not affect in child div? How to select <td> of the <table> with javascript? Maven: Non-resolvable parent POM