public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {// TODO Auto-generated method stubView root = inflater.inflate(layoutId(), container, false);return root;}
方法2:
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {// TODO Auto-generated method stubView root = inflater.inflate(layoutId(), null);return root;}
這兩種都可以,但是如果采用第二種,就不會繼承到母布局的參數信息。來看下文檔:
方法2調用的inflate()方法如下:
/*** Inflate a new view hierarchy from the specified xml resource. Throws* {@link InflateException} if there is an error.* * @param resource ID for an XML layout resource to load (e.g.,* <code>R.layout.main_page</code>)* @param root Optional view to be the parent of the generated hierarchy.* @return 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) {return inflate(resource, root, root != null);}
方法1調用的inflate()方法如下:
/*** Inflate a new view hierarchy from the specified xml resource. Throws* {@link InflateException} if there is an error.* * @param resource ID for an XML layout resource to load (e.g.,* <code>R.layout.main_page</code>)* @param root Optional view to be the parent of the generated hierarchy (if* <em>attachToRoot</em> is true), or else simply an object that* provides a set of LayoutParams values for root of the returned* hierarchy (if <em>attachToRoot</em> is false.)* @param 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.* @return 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.*/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();}}
如果root不為空,attachToRoot為false的情況下,文檔說的很明白:If false, root is only used to create the correct subclass of LayoutParams for the root view in the XML,即root只用來創建父布局的參數信息。而為true,則添加到父布局。因為我們控制fragment時要手動add/remove等,所以此處attachToRoot一定是false。