关于一个错误的记录:The specified child already has a parent. You must call removeView() on the child's parent

在构造一个包含又fragment的ViewPager时出现了错误:
Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
原因:提示说一个View已经有父视图了,但此时又将它添加到另一个父视图中。
出现这个原因的根源:我在fragment的onCreateView方法里不合理的绑定了视图。
错误写法:
  @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
       View view=  inflater.inflate(R.layout.fragment_firstcontent,container); 
     return view;
}

错误原因:我用此布局(R.layout.fragment_firstcontent)构建的视图view,指定其parent为container(默认值为view绑定到container)。而在ViewPager的Adapter中,view又需要在instantiateItem(ViewGroup container, int position)中指定这个container为view的parent(但此时view已经有parent了),从而造成了上述这个异常。
fragment中正确的写法为:
@Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
       View view=  inflater.inflate(R.layout.fragment_firstcontent,container,false);//表示view不绑定到container。
//或者  View view=  inflater.inflate(R.layout.fragment_firstcontent,null);
     return view;
}


LayoutInflater中相关方法的实现:

    public View inflate(int resource, ViewGroup root) {
        return inflate(resource, root, root != null);
    }

    public View inflate(int resource, 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();
        }
    }
从此可见,inflate(int resource,ViewGroup root)方法在root不能null的情况下会把resource绑定到root上。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值