LayoutInflater源码分析

来源:互联网 发布:pdf阅读器下载 知乎 编辑:程序博客网 时间:2024/06/11 18:06

一、LayoutInflater的作用:

将layout的xml布局文件实例化为View类对象。

二、获取LayoutInflater实例的方法:

LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);View layout = inflater.inflate(R.layout.main, null);
//该方法实质就是第一种方法,可参考源代码LayoutInflater inflater = LayoutInflater.from(context);View layout = inflater.inflate(R.layout.main, null);
//在Activity中可以使用LayoutInflater inflater = getLayoutInflater();View layout = inflater.inflate(R.layout.main, null);

三、inflate方法重载:

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

这四种使用方式中,我们最常用的是第一种方式。虽然重载了四个方法,但是前三种最终调用的还是第四种方式。第四种方式内部实现原理是利用Pull解析器,对Xml文件进行解析,然后返回View对象

四、inflate()方法返回值:

Returns - View 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.

1、如果提供root(不传null)时,返回值其实就是这个root,这个方法就是把xml解析成view之后挂载这个root下。

2、如果传null(不提供root),返回值就是xml布局里面的根节点。

即:如果参数root提供了,那么root就是根视图;否则填充的XML文件的根就是根视图。

通过源码分析可以看到,当提供root(不传null)时,如果attachToRoot传false,返回的是XML文件的根节点不是root。(参见下文源码分析)

五、setContentView和inflate的区别:

public class MyInflate extends Activity{    private TextView tv;    public void OnCreate(Bundle savedInstanceState){        super.onCreate(savedInstanceState);        //setContentView(R.layout.main);        //tv = (TextView) findViewById(R.id.tv);        LayoutInflater inflate = LayoutInflater.from(this);        View view = inflate.inflate(R.layout.main,null);-         setContentView(view);        tv = (TextView) findViewById(R.id.tv);    }}

1、上述注释掉的代码和没有注释掉的代码两种情况是相同的。

2、两者的区别:

(1)setContentView()一旦调用, layout就会立刻显示UI;
(2)inflate()只会把layout形成一个View对象,有需要时再用setContentView(view)显示出来。

一般在activity中,通过setContentView()将界面显示出来;但是如果在非activity中,这就需要LayoutInflater动态加载。

六、inflate(int resource, ViewGroup root, boolean attachToRoot)方法三个参数:

1、resource:需要加载布局文件的id。

2、root:需要附加到resource资源文件的根控件,什么意思呢?就是inflate()会返回一个View对象,如果第三个参数attachToRoot为true,就将这个root作为根对象返回,否则仅仅将这个root对象的LayoutParams属性附加到resource对象的根布局对象上,也就是将布局文件resource的布局参数转换为外层root可以接受的类型。

3、attachToRoot:是否将由布局文件实例化的View对象附加到传入的root并返回。

比如root是一个LinearLayout,自己要转换的resource里面有layout_width=”match_parent”,和layout_height=”match_parent”参数,但是这些参数没有外部环境,它们对应的对象都是ViewGroup.LayoutParams对象,root参数让系统将ViewGroup.LayoutParams对象转换为LinearLayout.LayoutParams对象。

七、如何保证item视图中的布局参数不变:

  1. 若我们采用 view = inflater.inflate(R.layout.item_list, null);方式填充视图,item布局中的根视图的layout_XX 属性会被忽略掉,然后设置成默认的包裹内容wrap_content方式。

  2. 如果我们想保证item的视图中的参数不被改变,我们需要使用view = inflater.inflate(R.layout.item_list, parent,false);这种方式进行视图的填充。

  3. 除了2使用这种方式,我们还可以设置item布局的根视图为包裹内容,然后设置内部控件的高度等属性,这样就不会修改显示方式了。

八、源码分析:

1、第一种重载方法:调用第二种重载方法

    public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {-        return inflate(resource, root, root != null);    }

2、第二种重载方法:调用第四种重载方法

    public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {        final Resources res = getContext().getResources();        if (DEBUG) {            Log.d(TAG, "INFLATING from resource: \"" + res.getResourceName(resource) + "\" ("                    + Integer.toHexString(resource) + ")");        }        // 获取指定资源的xml解析器        final XmlResourceParser parser = res.getLayout(resource);        try {-            return inflate(parser, root, attachToRoot);        } finally {            parser.close();        }    }

3、第三种重载方法:调用第四种重载方法

    public View inflate(XmlPullParser parser, @Nullable ViewGroup root) {        return inflate(parser, root, root != null);    }

4、第四种重载方法

    public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {        synchronized (mConstructorArgs) {            Trace.traceBegin(Trace.TRACE_TAG_VIEW, "inflate");            final Context inflaterContext = mContext;            final AttributeSet attrs = Xml.asAttributeSet(parser);            Context lastContext = (Context) mConstructorArgs[0];            mConstructorArgs[0] = inflaterContext;            // 默认返回的是父布局root            View result = root;            try {                // Look for the root node.                int type;                // 查找xml的开始标签                while ((type = parser.next()) != XmlPullParser.START_TAG &&                        type != XmlPullParser.END_DOCUMENT) {                    // Empty                }                if (type != XmlPullParser.START_TAG) {                    throw new InflateException(parser.getPositionDescription()                            + ": No start tag found!");                }                final String name = parser.getName();                if (DEBUG) {                    System.out.println("**************************");                    System.out.println("Creating root view: "                            + name);                    System.out.println("**************************");                }                if (TAG_MERGE.equals(name)) {                    if (root == null || !attachToRoot) {                        throw new InflateException("<merge /> can be used only with a valid "                                + "ViewGroup root and attachToRoot=true");                    }                    rInflate(parser, root, inflaterContext, attrs, false);                } else {                    // Temp is the root view that was found in the xml                    // 实例化xml布局的根view                    final View temp = createViewFromTag(root, name, inflaterContext, attrs);                    ViewGroup.LayoutParams params = null;                    if (root != null) {                        if (DEBUG) {                            System.out.println("Creating params from root: " +                                    root);                        }                        // Create layout params that match root, if supplied                        // 创建匹配root的布局参数                        params = root.generateLayoutParams(attrs);                        if (!attachToRoot) {                            // Set the layout params for temp if we are not                            // attaching. (If we are, we use addView, below)                            // 如果实例化的View不需要添加到父布局上,则直接将根据父布局生成的params参数设置给它即可                            temp.setLayoutParams(params);                        }                    }                    if (DEBUG) {                        System.out.println("-----> start inflating children");                    }                    // Inflate all children under temp against its context.                    rInflateChildren(parser, temp, attrs, true);                    if (DEBUG) {                        System.out.println("-----> done inflating children");                    }                    // We are supposed to attach all the views we found (int temp)                    // to root. Do that now.                    if (root != null && attachToRoot) {                        // 如果传入的父布局不为null,且attachToRoot为true,则将实例化的View加入到父布局root中                        root.addView(temp, params);                    }                    // Decide whether to return the root that was passed in or the                    // top view found in xml.                    // 如果父布局为null或者attachToRoot为false,则将返回值设置成我们实例化的View(这个地方是或者||)                    if (root == null || !attachToRoot) {                        result = temp;                    }                }            } catch (XmlPullParserException e) {                InflateException ex = new InflateException(e.getMessage());                ex.initCause(e);                throw ex;            } catch (Exception e) {                InflateException ex = new InflateException(                        parser.getPositionDescription()                                + ": " + e.getMessage());                ex.initCause(e);                throw ex;            } finally {                // Don't retain static reference on context.                mConstructorArgs[0] = lastContext;                mConstructorArgs[1] = null;            }            Trace.traceEnd(Trace.TRACE_TAG_VIEW);            return result;        }    }

(1)源码比较简单,看一下有汉语注释的地方应该就能比较清楚的了解实现原理了。

参考文献:
关于inflate的第3个参数
LayoutInflater——80%的Android程序员对它并不了解甚至错误使用
Android LayoutInflater.inflate源码分析

原创粉丝点击