您的位置:首页 > 其它

【错误】The specified child already has a parent.

2017-07-11 23:42 363 查看

【错误】The specified child already has a parent.

错误提示:java.lang.IllegalStateException:The specified child already has a parent.

出错的可能地点:Inflater.inflater() 主要是在fragment 中。或者ListView之中。

解决办法

将 view=inflater.inflate(R.layout.fragment_in_theaters,container);

改为 view=inflater.inflate(R.layout.fragment_in_theaters,container,false);

:R.layout.fragment_in_theaters 为你所填充的布局。container 父布局

错误原因:这个错误出现的原因,主要是由于对Inflater类的认识不够深入。而LayoutInflater类是在我们需要使用Fragment和listView等控件时常常需要使用的一个工具类。而这个类主要的作用就是将XML中的布局填充到父布局中去。

要分析错误出现的原因我们可以从源码中入手。

//一开始出错调用的方法
public View inflate(XmlPullParser parser, @Nullable ViewGroup root) {
return inflate(parser, root, root != null);
}

//正确调用时使用的方法
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
final Resources res = getContext().getResources();
if (DEBUG) {
Log.d(TAG, "INFLATING from resource: \"" + res.getResourceName(resource) + "\" ("
+ Integer.toHexString(resource) + ")");
}

final XmlResourceParser parser = res.getLayout(resource);
try {
return inflate(parser, root, attachToRoot);
} finally {
parser.close();
}


可以看到实际上两者最后都是调用了同一个方法

return inflate(parser, root, root != null);

return inflate(parser, root, attachToRoot);

而当我们在Fragment中填充布局时,父布局不为空时。那么我们传入的参数对于这两个方法的区别在于第三个参数 前者为true 后者为false(参见一开始传入的参数)。

那么接下来我们可以进入这个真正被调用的方法中看一看。

public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
//省略一大部分代码
if (root != null && attachToRoot) {
root.addView(temp, params);
}
//省略之后的代码


在实际调用当中我们可以看到,当root不为空,attachToRoot为true时将调用root.addView()方法。

而实际上的问题就发生在这之中。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐