java.lang.IllegalStateException: The specified child already has a parent.
You must call removeView() on the child's parent first.
也就是非法状态异常,它说这个特定的child已经有一个parent了,你必须在这个parent中首先调用removeView()方法,
才能继续你的内容。这里很明显这个child是一个View,一个子(child)View必须依赖于父(parent)View,如果你要
使用这个child,则必须通过parent,而你如果就是硬想使用这个child,那么就得让这个child与parent脱离父子关系
(即removeView())。ok,不是非常明白吧!我们先来比较这两个代码:
1. View android.view.LayoutInflater.inflate(int resource, ViewGroup root, boolean attachToRoot)
eg:View view = inflater.inflate(R.layout.activity_inner_advice, container,false);
2. View android.view.LayoutInflater.inflate(int resource, ViewGroup root)
eg:View view = inflater.inflate(R.layout.activity_inner_advice, container);
先说说这两个方法的区别:
第一个方法是根据attachToRoot判断是否将布局文件resource产生的view当做root的子类,也就是生成的view要依赖于父类root
如果attachToRoot是ture:就等同于第二个代码,view是root的子类;
如果attachToRoot是false:就是说view是单独存在的,不依赖root。
那么我们使用setContentView(view)显示view界面时,如果view有父类root,那么就会出现非法状态异常;反之,
如果view是独立的,没有父类root,就不会出现非法状态异常。
如果这个解释还是不明白,可以看这个例子:
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
LinearLayout parent = (LinearLayout) inflater.inflate(R.layout.main, null);
ImageView child = (ImageView)parent.findViewById(R.id.child);
setContentView(parent);
LayoutInflater为布局填充类,将main.xml文件inflate为LinearLayout文件,再得到child,即ImageView。然后就是通过
调用setContentView(parent)将这个布局main.xml显示出来。
下面的操作将会出现异常了:
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
LinearLayout parent = (LinearLayout) inflater.inflate(R.layout.main, null);
ImageView child = (ImageView)parent.findViewById(R.id.child);
setContentView(child);
也就是将上文setContentView(parent),中的parent换成child。
而这时在异常中它提示要再parent中调用removeView()。这里我们就听从指挥,在setContentView(child),之前添上
一句parent.removeView(child),这时就不会再调用setContentView(child)就不会异常了,当然当前显示的将只是一幅
图片了,而这时如果你调用setContentView(parent)的话将只显示文本内容,因为我们已经将child remove掉了。