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

最近公司新框架写布局全用代码实现不能用xml,写着写着运行一下发现没有布局显示。后发现是出现异常了,异常如下:

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

//看字面意思是子View已经存在于父View,你必须先调用该子View的父View的removeView()方法

解决办法:

//在addView之前加入如下代码

 ViewGroup parentViewGroup = (ViewGroup) 父View.getParent();
            if (parentViewGroup != null) {
                parentViewGroup.removeAllViews();
            }
 //之后就可以add子view了
      父View.addView(子View1);
      父View.addView(子View2);
      父View.addView(子View3);
发布了27 篇原创文章 · 获赞 187 · 访问量 14万+

猜你喜欢

转载自blog.csdn.net/Mr_wzc/article/details/77650656
今日推荐