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

【错误】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()方法。

而实际上的问题就发生在这之中。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值