In my app, 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 isn't occurring 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 gives me 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.
simply pass the attachtoroot argument as false
You can use this methode to check if a view has children or not .
If other solution is not working like:
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 got this message while trying to commit a fragment using attach to root to true instead of false, like so:
After doing:
It worked.
frameLayout.addView(bannerAdView);
<----- if you get error on this line the do like below..frameLayout.addView(bannerAdView);
<------ now added viewIn 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.Removing
addView()
helped to solve the problem.