Call removeView() on the child's parent first

时间:2024-06-08 20:05:20

extends:http://*.com/questions/6526874/call-removeview-on-the-childs-parent-first

Exception:

java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
at android.view.ViewGroup.addViewInner(ViewGroup.java:1976)
at android.view.ViewGroup.addView(ViewGroup.java:1871)
at android.view.ViewGroup.addView(ViewGroup.java:1828)
at android.view.ViewGroup.addView(ViewGroup.java:1808)
Solution:

((ViewGroup)scrollChildLayout.getParent()).removeView(scrollChildLayout); 

Use the child element to get a reference to the parent. Cast the parent to a ViewGroup so that you get access to the removeView method and use that.
 
     LinearLayout layout = initLayout();
for (int i = 0; i < items.size(); i++) {
View view = items.get(i);
((ViewGroup) view.getParent()).removeView(view);
layout.addView(view, lpLabel);
}
mLayout.addView(layout);