zoukankan      html  css  js  c++  java
  • Android LayoutInflater深度解析

    1、 题外话

    相信大家对LayoutInflate都不陌生,特别在ListView的Adapter的getView方法中基本都会出现,使用inflate方法去加载一个布局,用于ListView的每个Item的布局。Inflate有三个参数,我在初学Android的时候这么理解的:

    对于Inflate的三个参数(int resource, ViewGroup root, boolean attachToRoot)

    如果inflate(layoutId, null )则layoutId的最外层的控件的宽高是没有效果的

    如果inflate(layoutId, root, false ) 则认为和上面效果是一样的

    如果inflate(layoutId, root, true ) 则认为这样的话layoutId的最外层控件的宽高才能正常显示

    如果你也这么认为,那么你有就必要好好阅读这篇文章,因为这篇文章首先会验证上面的理解是错误的,然后从源码角度去解释,最后会从ViewGroup与View的角度去解释。

    2、 实践是验证真理的唯一标准

    下面我写一个特别常见的例子来验证上面的理解是错误的,一个特别简单的ListView,每个Item中放一个按钮:

    Activity的布局文件:

    [html] view plaincopy在CODE上查看代码片派生到我的代码片
     
    1. <ListView xmlns:android="http://schemas.android.com/apk/res/android"  
    2. xmlns:tools="http://schemas.android.com/tools"  
    3. android:id="@+id/id_listview"  
    4. android:layout_width="fill_parent"  
    5. android:layout_height="wrap_content" >  
    6. </ListView>  

    ListView的Item的布局文件:

    [html] view plaincopy在CODE上查看代码片派生到我的代码片
     
    1. <Button xmlns:android="http://schemas.android.com/apk/res/android"  
    2.     xmlns:tools="http://schemas.android.com/tools"  
    3.     android:id="@+id/id_btn"  
    4.     android:layout_width="120dp"  
    5.     android:layout_height="120dp" >  
    6.   
    7. </Button>  

    ListView的适配器:

    [java] view plaincopy在CODE上查看代码片派生到我的代码片
     
    1. package com.example.zhy_layoutinflater;  
    2.   
    3. import java.util.List;  
    4.   
    5. import android.content.Context;  
    6. import android.view.LayoutInflater;  
    7. import android.view.View;  
    8. import android.view.ViewGroup;  
    9. import android.widget.BaseAdapter;  
    10. import android.widget.Button;  
    11.   
    12. public class MyAdapter extends BaseAdapter  
    13. {  
    14.   
    15.     private LayoutInflater mInflater;  
    16.     private List<String> mDatas;  
    17.   
    18.     public MyAdapter(Context context, List<String> datas)  
    19.     {  
    20.         mInflater = LayoutInflater.from(context);  
    21.         mDatas = datas;  
    22.     }  
    23.   
    24.     @Override  
    25.     public int getCount()  
    26.     {  
    27.         return mDatas.size();  
    28.     }  
    29.   
    30.     @Override  
    31.     public Object getItem(int position)  
    32.     {  
    33.         return mDatas.get(position);  
    34.     }  
    35.   
    36.     @Override  
    37.     public long getItemId(int position)  
    38.     {  
    39.         return position;  
    40.     }  
    41.   
    42.     @Override  
    43.     public View getView(int position, View convertView, ViewGroup parent)  
    44.     {  
    45.   
    46.         ViewHolder holder = null;  
    47.         if (convertView == null)  
    48.         {  
    49.             holder = new ViewHolder();  
    50.             convertView = mInflater.inflate(R.layout.item, null);  
    51. //          convertView = mInflater.inflate(R.layout.item, parent ,false);  
    52. //          convertView = mInflater.inflate(R.layout.item, parent ,true);  
    53.             holder.mBtn = (Button) convertView.findViewById(R.id.id_btn);  
    54.             convertView.setTag(holder);  
    55.         } else  
    56.         {  
    57.             holder = (ViewHolder) convertView.getTag();  
    58.         }  
    59.   
    60.         holder.mBtn.setText(mDatas.get(position));  
    61.   
    62.         return convertView;  
    63.     }  
    64.   
    65.     private final class ViewHolder  
    66.     {  
    67.         Button mBtn;  
    68.     }  
    69. }  


    主Activity:

    [java] view plaincopy在CODE上查看代码片派生到我的代码片
     
    1. package com.example.zhy_layoutinflater;  
    2.   
    3. import java.util.Arrays;  
    4. import java.util.List;  
    5.   
    6. import android.app.Activity;  
    7. import android.os.Bundle;  
    8. import android.widget.ListView;  
    9.   
    10. public class MainActivity extends Activity  
    11. {  
    12.   
    13.     private ListView mListView;  
    14.     private MyAdapter mAdapter;  
    15.     private List<String> mDatas = Arrays.asList("Hello", "Java", "Android");  
    16.   
    17.     @Override  
    18.     protected void onCreate(Bundle savedInstanceState)  
    19.     {  
    20.         super.onCreate(savedInstanceState);  
    21.         setContentView(R.layout.activity_main);  
    22.   
    23.         mListView = (ListView) findViewById(R.id.id_listview);  
    24.         mAdapter = new MyAdapter(this, mDatas);  
    25.         mListView.setAdapter(mAdapter);  
    26.   
    27.   
    28.     }  
    29.   
    30. }  

    好了,相信大家对这个例子都再熟悉不过了,没啥好说的,我们主要关注getView里面的inflate那行代码:下面我依次把getView里的写成:
    1、convertView = mInflater.inflate(R.layout.item, null);
    2、convertView = mInflater.inflate(R.layout.item, parent ,false);
    3、convertView = mInflater.inflate(R.layout.item, parent ,true);
    分别看效果图:

    图1:

    图2:

    图3:

    [html] view plaincopy在CODE上查看代码片派生到我的代码片
     
    1. FATAL EXCEPTION: main  
    2. java.lang.UnsupportedOperationException:   
    3. addView(View, LayoutParams) is not supported in AdapterView  


    嗯,没错没有图3,第三种写法会报错。

    由上面三行代码的变化,产生3个不同的结果,可以看到

    inflater(resId, null )的确不能正确处理宽高的值,但是inflater(resId,parent,false)并非和inflater(resId, null )效果一致,它可以看出完美的显示了宽和高。

    而inflater(resId,parent,true)报错了(错误的原因在解析源码的时候说)。

    由此可见:文章开始提出的理解是绝对错误的。

    3、源码解析

    下面我通过源码来解释,这三种写法真正的差异

    这三个方法,最终都会执行下面的代码:

    [java] view plaincopy在CODE上查看代码片派生到我的代码片
     
    1. public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {  
    2.        synchronized (mConstructorArgs) {  
    3.            final AttributeSet attrs = Xml.asAttributeSet(parser);  
    4.            Context lastContext = (Context)mConstructorArgs[0];  
    5.            mConstructorArgs[0] = mContext;  
    6.            View result = root;  
    7.   
    8.            try {  
    9.                // Look for the root node.  
    10.                int type;  
    11.                while ((type = parser.next()) != XmlPullParser.START_TAG &&  
    12.                        type != XmlPullParser.END_DOCUMENT) {  
    13.                    // Empty  
    14.                }  
    15.   
    16.                if (type != XmlPullParser.START_TAG) {  
    17.                    throw new InflateException(parser.getPositionDescription()  
    18.                            + ": No start tag found!");  
    19.                }  
    20.   
    21.                final String name = parser.getName();  
    22.                  
    23.                if (DEBUG) {  
    24.                    System.out.println("**************************");  
    25.                    System.out.println("Creating root view: "  
    26.                            + name);  
    27.                    System.out.println("**************************");  
    28.                }  
    29.   
    30.                if (TAG_MERGE.equals(name)) {  
    31.                    if (root == null || !attachToRoot) {  
    32.                        throw new InflateException("<merge /> can be used only with a valid "  
    33.                                + "ViewGroup root and attachToRoot=true");  
    34.                    }  
    35.   
    36.                    rInflate(parser, root, attrs, false);  
    37.                } else {  
    38.                    // Temp is the root view that was found in the xml  
    39.                    View temp;  
    40.                    if (TAG_1995.equals(name)) {  
    41.                        temp = new BlinkLayout(mContext, attrs);  
    42.                    } else {  
    43.                        temp = createViewFromTag(root, name, attrs);  
    44.                    }  
    45.   
    46.                    ViewGroup.LayoutParams params = null;  
    47.   
    48.                    if (root != null) {  
    49.                        if (DEBUG) {  
    50.                            System.out.println("Creating params from root: " +  
    51.                                    root);  
    52.                        }  
    53.                        // Create layout params that match root, if supplied  
    54.                        params = root.generateLayoutParams(attrs);  
    55.                        if (!attachToRoot) {  
    56.                            // Set the layout params for temp if we are not  
    57.                            // attaching. (If we are, we use addView, below)  
    58.                            temp.setLayoutParams(params);  
    59.                        }  
    60.                    }  
    61.   
    62.                    if (DEBUG) {  
    63.                        System.out.println("-----> start inflating children");  
    64.                    }  
    65.                    // Inflate all children under temp  
    66.                    rInflate(parser, temp, attrs, true);  
    67.                    if (DEBUG) {  
    68.                        System.out.println("-----> done inflating children");  
    69.                    }  
    70.   
    71.                    // We are supposed to attach all the views we found (int temp)  
    72.                    // to root. Do that now.  
    73.                    if (root != null && attachToRoot) {  
    74.                        root.addView(temp, params);  
    75.                    }  
    76.   
    77.                    // Decide whether to return the root that was passed in or the  
    78.                    // top view found in xml.  
    79.                    if (root == null || !attachToRoot) {  
    80.                        result = temp;  
    81.                    }  
    82.                }  
    83.   
    84.            } catch (XmlPullParserException e) {  
    85.                InflateException ex = new InflateException(e.getMessage());  
    86.                ex.initCause(e);  
    87.                throw ex;  
    88.            } catch (IOException e) {  
    89.                InflateException ex = new InflateException(  
    90.                        parser.getPositionDescription()  
    91.                        + ": " + e.getMessage());  
    92.                ex.initCause(e);  
    93.                throw ex;  
    94.            } finally {  
    95.                // Don't retain static reference on context.  
    96.                mConstructorArgs[0] = lastContext;  
    97.                mConstructorArgs[1] = null;  
    98.            }  
    99.   
    100.            return result;  
    101.        }  
    102.    }  


    第6行:首先声明了View result = root ;//最终返回值为result

    第43行执行了:temp = createViewFromTag(root, name, attrs);创建了View

    然后直接看48-59:

    [java] view plaincopy在CODE上查看代码片派生到我的代码片
     
    1. if(root!=null)  
    2. {  
    3.  params = root.generateLayoutParams(attrs);  
    4.         if (!attachToRoot)  
    5.  {  
    6.    temp.setLayoutParams(params);  
    7.  }  
    8. }  

    可以看到,当root不为null,attachToRoot为false时,为temp设置了LayoutParams.

    继续往下,看73-75行:

    [java] view plaincopy在CODE上查看代码片派生到我的代码片
     
    1. if (root != null && attachToRoot)  
    2. {  
    3. root.addView(temp, params);  
    4. }  

    当root不为null,attachToRoot为true时,将tmp按照params添加到root中。

    然后78-81行:

    [java] view plaincopy在CODE上查看代码片派生到我的代码片
     
    1. if (root == null || !attachToRoot) {   
    2. result = temp;   
    3. }   


    如果root为null,或者attachToRoot为false则,将temp赋值给result。

    最后返回result。

    从上面的分析已经可以看出:

    Inflate(resId , null ) 只创建temp ,返回temp

    Inflate(resId , parent, false )创建temp,然后执行temp.setLayoutParams(params);返回temp

    Inflate(resId , parent, true ) 创建temp,然后执行root.addView(temp, params);最后返回root

    由上面已经能够解释:

    Inflate(resId , null )不能正确处理宽和高是因为:layout_width,layout_height是相对了父级设置的,必须与父级的LayoutParams一致。而此temp的getLayoutParams为null

    Inflate(resId , parent,false ) 可以正确处理,因为temp.setLayoutParams(params);这个params正是root.generateLayoutParams(attrs);得到的。

    Inflate(resId , parent,true )不仅能够正确的处理,而且已经把resId这个view加入到了parent,并且返回的是parent,和以上两者返回值有绝对的区别,还记得文章前面的例子上,MyAdapter里面的getView报的错误: 

    [html] view plaincopy在CODE上查看代码片派生到我的代码片
     
    1. java.lang.UnsupportedOperationException:   
    2. addView(View, LayoutParams) is not supported in AdapterView  


    这是因为源码中调用了root.addView(temp, params);而此时的root是我们的ListView,ListView为AdapterView的子类:
    直接看AdapterView的源码:

    [java] view plaincopy在CODE上查看代码片派生到我的代码片
     
    1. @Override  
    2.   public void addView(View child) {  
    3.         throw new UnsupportedOperationException("addView(View) is not supported in AdapterView");  
    4.   }  


    可以看到这个错误为啥产生了。

    4、 进一步的解析

    上面我根据源码得出的结论可能大家还是有一丝的迷惑,我再写个例子论证我们上面得出的结论:
    主布局文件:

    [html] view plaincopy在CODE上查看代码片派生到我的代码片
     
    1. <Button xmlns:android="http://schemas.android.com/apk/res/android"  
    2.     xmlns:tools="http://schemas.android.com/tools"  
    3.     android:id="@+id/id_btn"  
    4.     android:layout_width="120dp"  
    5.     android:layout_height="120dp"  
    6.     android:text="Button" >  
    7. </Button>  


    主Activity:

    [java] view plaincopy在CODE上查看代码片派生到我的代码片
     
    1. package com.example.zhy_layoutinflater;  
    2.   
    3. import android.app.ListActivity;  
    4. import android.os.Bundle;  
    5. import android.util.Log;  
    6. import android.view.LayoutInflater;  
    7. import android.view.View;  
    8. import android.view.ViewGroup;  
    9.   
    10. public class MainActivity extends ListActivity  
    11. {  
    12.   
    13.   
    14.     private LayoutInflater mInflater;  
    15.   
    16.     @Override  
    17.     protected void onCreate(Bundle savedInstanceState)  
    18.     {  
    19.         super.onCreate(savedInstanceState);  
    20.   
    21.         mInflater = LayoutInflater.from(this);  
    22.   
    23.         View view1 = mInflater.inflate(R.layout.activity_main, null);  
    24.         View view2 = mInflater.inflate(R.layout.activity_main,  
    25.                 (ViewGroup)findViewById(android.R.id.content), false);  
    26.         View view3 = mInflater.inflate(R.layout.activity_main,  
    27.                 (ViewGroup)findViewById(android.R.id.content), true);  
    28.   
    29.         Log.e("TAG", "view1 = " + view1  +" , view1.layoutParams = " + view1.getLayoutParams());  
    30.         Log.e("TAG", "view2 = " + view2  +" , view2.layoutParams = " + view2.getLayoutParams());  
    31.         Log.e("TAG", "view3 = " + view3  );  
    32.   
    33.     }  
    34.   
    35. }  


    可以看到我们的主Activity并没有执行setContentView,仅仅执行了LayoutInflater的3个方法。
    注:parent我们用的是Activity的内容区域:即android.R.id.content,是一个FrameLayout,我们在setContentView(resId)时,其实系统会自动为了包上一层FrameLayout(id=content)。

    按照我们上面的说法:

    view1的layoutParams 应该为null
    view2的layoutParams 应该不为null,且为FrameLayout.LayoutParams
    view3为FrameLayout,且将这个button添加到Activity的内容区域了(因为R.id.content代表Actvity内容区域)

    下面看一下输出结果,和Activity的展示:

    [html] view plaincopy在CODE上查看代码片派生到我的代码片
     
    1. 07-27 14:17:36.703: E/TAG(2911): view1 = android.widget.Button@429d1660 , view1.layoutParams = null  
    2. 07-27 14:17:36.703: E/TAG(2911): view2 = android.widget.Button@42a0e120 , view2.layoutParams = android.widget.FrameLayout$LayoutParams@42a0e9a0  
    3. 07-27 14:17:36.703: E/TAG(2911): view3 = android.widget.FrameLayout@42a0a240  

    效果图:

    可见,虽然我们没有执行setContentView,但是依然可以看到绘制的控件,是因为

    View view3 = mInflater.inflate(R.layout.activity_main,(ViewGroup)findViewById(android.R.id.content), true);

    这个方法内部已经执行了root.addView(temp , params); 上面已经解析过了。

    也可以看出:和我们的推测完全一致,到此已经完全说明了inflate3个重载的方法的区别。相信大家以后在使用时也能选择出最好的方式。不过下面准备从ViewGroup和View的角度来说一下,为啥layoutParams为null,就不能这确的处理。

    5、从ViewGroup和View的角度来解析

    如果大家对自定义ViewGroup和自定义View有一定的掌握,肯定不会对onMeasure方法陌生:
    ViewGroup的onMeasure方法所做的是:

    为childView设置测量模式和测量出来的值。

    如何设置呢?就是根据LayoutParams。
    如果childView的宽为:LayoutParams. MATCH_PARENT,则设置模式为MeasureSpec.EXACTLY,且为childView计算宽度。
    如果childView的宽为:固定值(即大于0),则设置模式为MeasureSpec.EXACTLY,且将lp.width直接作为childView的宽度。
    如果childView的宽为:LayoutParams. WRAP_CONTENT,则设置模式为:MeasureSpec.AT_MOST
    高度与宽度类似。

    View的onMeasure方法:
    主要做的就是根据ViewGroup传入的测量模式和测量值,计算自己应该的宽和高:
    一般是这样的流程:
    如果宽的模式是AT_MOST:则自己计算宽的值。
    如果宽的模式是EXACTLY:则直接使用MeasureSpec.getSize(widthMeasureSpec);

    对于最后一块,如果不清楚,不要紧,以后我会在自定义ViewGroup和自定义View时详细讲解的。

    大概就是这样的流程,真正的绘制过程肯定比这个要复杂,就是为了说明如果View的宽和高如果设置为准确值,则一定依赖于LayoutParams,所以我们的inflate(resId,null)才没能正确处理宽和高。

  • 相关阅读:
    C# 获取指定目录下所有文件信息、移动目录、拷贝目录
    土地利用数据库地图自动缩编软件--地图缩编
    全国不动产登记交流
    [记录]好用的文件上传插件webuploader
    Petapoco Update在使用匿名对象修改时提示“给定关键字不在字典中”
    解决在MySQL使用PetaPoco T4生成数据的实体时得到当前MySQL数据库下所有表的错误方法
    [知识积累]MySQL外键约束条件
    Js判断QQ在线状态不准确的解决办法
    稍带迷茫的秋日小记
    假如你有个idea,你将怎么去实现它?
  • 原文地址:https://www.cnblogs.com/bdbw2012/p/4673618.html
Copyright © 2011-2022 走看看