java.lang.IllegalStateException: The specified child already has a parent. You must call removeView(

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掉了。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值