java.lang.IllegalStateException:The specified child already has a parent异常万能解决方案:removeView

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

这个异常让人很头疼,你必须要在parent上调用removeView移除掉你要重复使用的这个view才可以,有时候不知道你的view被哪一个parent给绑定了,所以很头疼。下面给出解绑方法的思路:

解决思路1:帮孩子找父母,然后断绝亲子关系:

 

三步走:

假设你的子view就叫child_view

1、 找出parent

ViewParent parent = child_view.getParent();

正常想法,直接parent.removeView不就可以了嘛,可是你会发现ViewParent没有removeView方法。接下来:

 

2、找出这个parent具体是什么类型

if(parent!=null)
    Log.i("who_are_you",parent.getClass().toString());

直接输出,然后你会看到输出的类型是什么,我这边是FrameLayout,真相大白,接下来解绑:



3、直接强转,解绑:

FrameLayout mFrameLayout = (FrameLayout)parent;
mFrameLayout.removeView(child_view);

熟悉更多android代码以后,才发现其实有更简单的方法,只需一行代码:

解决思路2:给孩子找个继父母,然后断绝亲子关系:

((ViewGroup)childView.getParent()).removeView(childView);

当然,实际开发你得判断这个childView的父view是否为空 。

 

OK,解完,收工。 

转载注明出处:https://blog.csdn.net/qq_35584878/article/details/93038872

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章