inflater参数

来源:互联网 发布:知乎日报 rss地址 编辑:程序博客网 时间:2024/06/04 19:27

LayoutInflater的inflate方法,在fragment的onCreateView方法中经常用到:

[java] view plain copy
  1. public View onCreateView(LayoutInflater inflater, ViewGroup container,  
  2.         Bundle savedInstanceState) {  

LayoutInflater的inflate方法一共有四种,但我们日常用经常用到的就只有这两种:

[java] view plain copy
  1. public View inflate(int resource, ViewGroup root) {  
  2.     return inflate(resource, root, root != null);  
  3. }  

[java] view plain copy
  1. public View inflate(int resource, ViewGroup root, boolean attachToRoot) {  
  2.     if (DEBUG) System.out.println("INFLATING from resource: " + resource);  
  3.     XmlResourceParser parser = getContext().getResources().getLayout(resource);  
  4.     try {  
  5.         return inflate(parser, root, attachToRoot);  
  6.     } finally {  
  7.         parser.close();  
  8.     }  
  9. }  


所以,这里直接介绍里面调用这个方法即可:

[java] view plain copy
  1. public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot)  

在这个方法里面,上半部分为xml解析的代码,这里就不贴出来,确实没什么东西可看。直接看中间部分的代码:

[java] view plain copy
  1. ViewGroup.LayoutParams params = null;  
  2.   
  3. if (root != null) {  
  4.     if (DEBUG) {  
  5.         System.out.println("Creating params from root: " +  
  6.                 root);  
  7.     }  
  8.     // Create layout params that match root, if supplied  
  9.     params = root.generateLayoutParams(attrs);  
  10.     if (!attachToRoot) {  
  11.         // Set the layout params for temp if we are not  
  12.         // attaching. (If we are, we use addView, below)  
  13.         temp.setLayoutParams(params);  
  14.     }  
  15. }  


params = root.generateLayoutParams(attrs);

这段的意思是:如果调用inflate方法,传入了ViewGroup root参数,则会从root中得到由layout_width和layout_height组成的LayoutParams,在attachToRoot设置为false的话,就会对我们加载的视图View设置该LayoutParams。

接着往下看:

[java] view plain copy
  1. // We are supposed to attach all the views we found (int temp)  
  2. // to root. Do that now.  
  3. if (root != null && attachToRoot) {  
  4.     root.addView(temp, params);  
  5. }  
  6.   
  7. // Decide whether to return the root that was passed in or the  
  8. // top view found in xml.  
  9. if (root == null || !attachToRoot) {  
  10.     result = temp;  
  11. }  


root.addView(temp, params);

如果设置了ViewGroup root参数,且attachToRoot设置为true的话,则将我们加载的视图做为子视图添加到root视图中。


如果我们ViewGroup root设置为空的话,就直接返回我们创建的视图;如果root不为空,且attachToRoot设置为false的话,就返回上面那段:对我们加载的视图View设置该LayoutParams。


转载出处:http://blog.csdn.net/xyz_fly/article/details/21301303

0 0