"The specified child already has a parent. you must call removeview() on the child's parent first" Code Answer:

When you try to switch between two layouts again and again. And you are receiving an error when attempting to close the fragment by calling activity.onBackPressed():

 Error

  • Caused by java.lang.IllegalStateException
  • The specified child already has a parent. You must call removeView() on the child’s parent first.

 

So here is the solution. But Before destroying You have to clear fragments parent.

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

on Jan 01, 1970
// TEXTVIEW
if(tv.getParent() != null) {
    ((ViewGroup)tv.getParent()).removeView(tv); // <- fix
}
layout.addView(tv); //  <==========  ERROR IN THIS LINE DURING 2ND RUN
// EDITTEXT

Add Comment

1

Note that when it is the first attempt at your layout, no error occurs. But when you switch to a different vacant layout and tried a second attempt, it will show that error. This error also appears While trying to enlarge a FragmentDialog containing a RecyclerView.

I know this question has been asked many times, so here is the answer.

Java answers related to "the specified child already has a parent. you must call removeview() on the child's parent first."

View All Java queries

Java queries related to "the specified child already has a parent. you must call removeview() on the child's parent first."

Browse Other Code Languages

CodeProZone