Call removeView() on the child's parent first

extends:http://stackoverflow.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);

原文地址:https://www.cnblogs.com/niray/p/4415516.html