During android development, you may encounter the same problem in different situations:
java.lang.IllegalStateException The specified child already has a parent. You must call removeView() on the child's parent first.
That is, an invalid state exception. It indicates that this specific child already has a parent. You must first call the removeView () method in this parent to continue your content. Obviously, this child is a View. A child View must depend on the parent View. If you want to use this child View, you must use the parent, if you want to use this child, you have to disassociate the child from the parent (removeView ())...... Let's take a simple example to illustrate how the province is messy and you are dizzy.
Create a new project. The layout file contains only one TextView and one ImageView. The layout mode is linear layout (For details, refer to the source code below). The running result is to display a text and an image,
In the onCreate () method of the Activity, we usually use the following method to use the layout file main. xml.
setContentView(R.layout.main);
Here, to explain the exception that we want to explain today, we will change the layout File Usage method by commenting out the above line of code and replacing it with the following code:
// Obtain the Infalter object
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);LinearLayout parent = (LinearLayout) inflater.inflate(R.layout.main, null);ImageView child = (ImageView)parent.findViewById(R.id.child); setContentView(parent);
LayoutInflater is the layout filling class. If you do not understand it, you can check it yourself, or if you have the opportunity to introduce it in your blog, and then click main. the xml file inflate is the LinearLayout file, and then the child, that is, ImageView, is obtained. Then, the layout main. xml is displayed by calling setContentView (parent). The result is the same as that obtained by using only setContentView (R. layout. main.
The following operations will cause exceptions. Please note:
setContentView(child);
That is, replace the parent in setContentView (parent) with child. See the following for exceptions:
In this case, the system prompts you to call removeView () in the parent (). Here we will follow the command and add a parent before setContentView (child. removeView (child), then it will not call setContentView (child) Again, it will not be abnormal, of course, the current display will only be an image, and if you call setContentView (parent) only the text content will be displayed, because we have removed the child.
The Code is as follows:
Http://download.csdn.net/detail/yaolingrui/4129192