码迷,mamicode.com
首页 > 其他好文 > 详细

关于异常“The specified child already has a parent. You

时间:2015-09-08 09:43:55      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:

android开发过程中,有时会在不同情况下遇到同种问题:

[java] view plaincopy

  1. 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,一个子(childView必须依赖于父(parentView,如果你要使用这个child,则必须通过parent,而你如果就是硬想使用这个child,那么就得让这个childparent脱离父子关系(即removeView())……算了还是举个简单的例子来说明一下,省的我说的乱七八糟,你听的也晕。

新建一个项目,布局文件中仅包含一个TextView和一个ImageView,布局方式是线性布局(具体可以参考后面的源代码),运行的结果就是显示一个文本和一张图片,

ActivityonCreate()方法中,我们通常使用以下这种方式来使用布局文件main.xml

[java] view plaincopy

  1. setContentView(R.layout.main);  


这里为了解释今天要讲解的这个异常,换一种布局文件的使用方式,即把上面的那一行代码注释掉,换成以下代码:

//获取Infalter对象

[java] view plaincopy

  1. LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);  

  2. LinearLayout parent = (LinearLayout) inflater.inflate(R.layout.main, null);  

  3. ImageView child = (ImageView)parent.findViewById(R.id.child);          

  4. setContentView(parent);  


LayoutInflater为布局填充类,不明白的可以自己查,或者有机会我将在博客中介绍一下,然后是将main.xml文件inflateLinearLayout文件,再得到child,即ImageView。然后就是通过调用setContentView(parent)将这个布局main.xml显示出来,这时得到的效果和仅使用setContentView(R.layout.main)这句代码得到的效果一样。

下面的操作将会出现异常了,大家注意:

[java] view plaincopy

  1. setContentView(child);  

也就是将上文setContentView(parent),中的parent换成child。异常请看如下截图:

技术分享

而这时在异常中它提示要再parent中调用removeView()。这里我们就听从指挥,在setContentView(child),之前添上一句parent.removeView(child),这时就不会再调用setContentView(child)就不会异常了,当然当前显示的将只是一幅图片了,而这时如果你调用setContentView(parent)的话将只显示文本内容,因为我们已经将child remove掉了嘛。

代码如下:

http://download.csdn.net/detail/yaolingrui/4129192


关于异常“The specified child already has a parent. You

标签:

原文地址:http://my.oschina.net/u/1177694/blog/502618

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!