Fragment error:The specified child already has a parent.

来源:互联网 发布:jmeter for mac安装 编辑:程序博客网 时间:2024/05/29 18:02

前提:用RadioGroup写了一个底边导航,fragment_container用FrameLayout布局。

报错代码在:

@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){mView = inflater.inflate(R.layout.fragment_registration, container);return mView;}
这样,就会报错:

java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.


但是,如果改成:

@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){mView = inflater.inflate(R.layout.fragment_registration, null);return mView;}
就可以成功编译。


为什么呢?


。。。。

下面解惑一下:

先看一Android Developer的描述:

public View inflate (int resource, ViewGroup root)

Added in API level 1

Inflate a new view hierarchy from the specified xml resource. Throws InflateException if there is an error.

Parameters
resourceID for an XML layout resource to load (e.g., R.layout.main_page)rootOptional view to be the parent of the generated hierarchy.
Returns
  • The root View of the inflated hierarchy. If root was supplied, this is the root View; otherwise it is the root of the inflated XML file.

public View inflate (int resource, ViewGroup root, boolean attachToRoot)

Added in API level 1

Inflate a new view hierarchy from the specified xml resource. Throws InflateException if there is an error.

Parameters
resourceID for an XML layout resource to load (e.g., R.layout.main_page)rootOptional view to be the parent of the generated hierarchy (if attachToRoot is true), or else simply an object that provides a set of LayoutParams values for root of the returned hierarchy (if attachToRoot is false.)attachToRootWhether the inflated hierarchy should be attached to the root parameter? If false, root is only used to create the correct subclass of LayoutParams for the root view in the XML.
Returns
  • The root View of the inflated hierarchy. If root was supplied and attachToRoot is true, this is root; otherwise it is the root of the inflated XML file.
重点在于理解 returns 的描述:
  • The root View of the inflated hierarchy. If root was supplied, this is the root View; otherwise it is the root of the inflated XML file.

返回的是:填充的层次结构的根视图。如果root参数提供了,那么这就是根视图,否则将返回填充xml文件的根视图,即R.id.fragment_container.

通过测试得知:

onCreateView()中的ViewGroup container获取器id(即,container.getId())与R.id.fragment_container 是一致的。


另外,inflater.inflate(R.layout.fragment_one, container, true);

    或者inflater.inflate(R.layout.fragment_one, container);这两种指定root的方法,在自定义控件时常被用到。

而在fragment中,不需要指定root。设为null即可。

即,inflater.inflate(R.layout.fragment_one, null, false);

或者inflater.inflate(R.layout.fragment_one, container, false);

或者inflater.inflate(R.layout.fragment_one, null);



0 0
原创粉丝点击