前提:用RadioGroup写了一个底边导航,fragment_container用FrameLayout布局。
报错代码在:
@Override public 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.
但是,如果改成:
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mView = inflater.inflate(R.layout.fragment_registration, null); return mView; }就可以成功编译。
为什么呢?
。。。。
下面解惑一下:
先看一Android Developer的描述:
Inflate a new view hierarchy from the specified xml resource. Throws InflateException
if there is an error.
resource | ID for an XML layout resource to load (e.g., R.layout.main_page ) |
---|---|
root | Optional view to be the parent of the generated hierarchy. |
Inflate a new view hierarchy from the specified xml resource. Throws InflateException
if there is an error.
resource | ID for an XML layout resource to load (e.g., R.layout.main_page ) |
---|---|
root | Optional 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.) |
attachToRoot | Whether 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. |
返回的是:填充的层次结构的根视图。如果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);