当我们调用ViewGroup的addView()方法时
public void addView(View child) {
addView(child, -1);
}
最终会调用addViewInLayout()方法
private void addViewInner(View child, int index, LayoutParams params,
boolean preventRequestLayout) {
if (mTransition != null) {
// Don't prevent other add transitions from completing, but cancel remove
// transitions to let them complete the process before we add to the container
mTransition.cancel(LayoutTransition.DISAPPEARING);
}
if (child.getParent() != null) {
throw new IllegalStateException("The specified child already has a parent. " +
"You must call removeView() on the child's parent first.");
}
...
if (index < 0) {
index = mChildrenCount;
}
...
}
由此可知,产生这个错误的原因是child.getParent() != null,即当前View的parent不为空,之前有被加到过ViewGroup里面
解决办法:调用父view的removeAllViews()或者removeView()方法。如果不知道父view,可以使用这个方法
<pre name="code" class="java">public static void removeParent(View v){
ViewParent parent = v.getParent();
if(parent instanceof ViewGroup){
ViewGroup group=(ViewGroup) parent;
group.removeView(v);
}
}