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

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

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


今天写代码要给AlertDialog加一个自定义的View 然后就报错了,报错是因为再一次触发加载布局view的时候由于在viewgroup里已经有了这个布局所以不能再一次加载,必须先要移除经过分析发现了解决办法

 

一开始是这样写的

<span style="white-space:pre">	</span>view = getLayoutInflater().from(MainActivity2.this).inflate(R.layout.numberpicker,null);     
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity2.this);     
        builder.setView(view);


后来这样写 就可以了
<span style="font-size:24px;">     </span><span style="font-size:14px;"> view = getLayoutInflater().from(MainActivity2.this).inflate(R.layout.numberpicker,null);
        ViewGroup vg=(ViewGroup)view.getParent();
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity2.this);
        if(vg!=null){

           vg.removeView(view);
        }
        builder.setView(view);</span>