Corneliu Corneliu - 19 days ago 6
Android Question

You must call removeView() on the child's parent first

i have :

mContainer.removeAllViewsInLayout();
mContainer.addView(nViews)


But i recive the error :

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


what is wrong ?

Answer

There is an important difference between removeAllViewsInLayout() and removeAllViews().

The former may not remove all the views, the latter will remove all the views. Unless you are doing your own logic to figure which views were removed in removeAllViewsInLayout(), you are likely trying to add duplicate views to your layout.

As a matter of fact, removeAllViewsInLayout() comes with this warning:

Do not call this method unless you are extending ViewGroup and understand the view measuring and layout pipeline.

Based on your post, I am assuming that you are not extending ViewGroup and properly analyzing the measuring/layout pipeline, and thus should not be calling that method.

However, if mContainer is not actual parent of nViews, clearing mContainer will not suffice. In that case you have to remove nViews using removeView() method on it's real parent before you can add it to mContainer.