天天看点

关于LayoutInflater的inflate方法分析

LayoutInflater 中的inflate方法共有四个重载

return inflate(resource, root, root != null);
    }
           
public View inflate(XmlPullParser parser, ViewGroup root) {
        return inflate(parser, root, root != null);
    }
           
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();
        }
    }
           
public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {....省略.}
           

这四个方法中实现inflate实际功能的是第四个方法,只是前三个方法会根据参数的不同去默认的设置一些参数,然后去调用第四个方法

前俩个方法区别只是传入的源不同,他们都会对root进行判断,如果root=null 则attachToRoot则为false,否则则为true.

第三个方法是将xml转换成一个paraser,其他参数不变,调用第四个方法。

所以inflate方法的关键问题就在于root和attachToRoot这俩个参数的含义

下面贴出第四个方法的源码

public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {
        synchronized (mConstructorArgs) {
            Trace.traceBegin(Trace.TRACE_TAG_VIEW, "inflate");

            final AttributeSet attrs = Xml.asAttributeSet(parser);
            Context lastContext = (Context)mConstructorArgs[0];
            mConstructorArgs[0] = mContext;
           
<span style="white-space:pre">		</span>//默认情况下返回的结果为root
            View result = root;

            try {
                // Look for the root node.
                int type;
                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");
                    }
<span style="white-space:pre">			</span>//如果root==null 并且attachToRoot为false时,则不合法,这样返回的View确是
           
<span style="white-space:pre">			</span>//是我们要加载的View但这样会丢失View的LayoutParam属性
                    rInflate(parser, root, attrs, false, false);
                } else {
                    // Temp is the root view that was found in the xml
           
<span style="white-space:pre">			</span>//这里根据标签名生成一个View,这里创建了我们要加载的View
                    final View temp = createViewFromTag(root, name, attrs, false);

                    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
           
<span style="white-space:pre">			</span>//根据root去生成一个layoutparam
                        params = root.generateLayoutParams(attrs);
                        if (!attachToRoot) {
                            // Set the layout params for temp if we are not
                            // attaching. (If we are, we use addView, below)
           
<span style="white-space:pre">				</span>//如果root!= null && attachToRoot== false 
           
<span style="white-space:pre">				</span>//将会给我们加载的View设置一个LayoutParams属性 所以这样设置会保留我们要加载的View的LayoutParmas属性,显示为
           
<span style="white-space:pre">				</span>//我们预期的结果
                            temp.setLayoutParams(params);
                        }
                    }

                    if (DEBUG) {
                        System.out.println("-----> start inflating children");
                    }
                    // Inflate all children under temp
                    rInflate(parser, temp, attrs, true, 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.
           
<span style="white-space:pre">			</span>//如果root!= null && attachToRoot = true 则
           
<span style="white-space:pre">			</span>//<span style="font-family: Arial, Helvetica, sans-serif;">params = root.generateLayoutParams(attrs); 但是我们要加载的View的params确没有被设置</span>
           
<span style="font-family:Arial, Helvetica, sans-serif;"><span style="white-space:pre">						</span>//这时会将我们要加载的View添加到root中,并将root返回
</span>                    if (root != null && attachToRoot) {
                        root.addView(temp, params);
                    }

                    // Decide whether to return the root that was passed in or the
                    // top view found in xml.
                    if (root == null || !attachToRoot) {
                        result = temp;
                    }
                }

            } catch (XmlPullParserException e) {
                InflateException ex = new InflateException(e.getMessage());
                ex.initCause(e);
                throw ex;
            } catch (IOException 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;
        }
    }
           

所以root 和attachToRoot参数的不同,inflate将会有以下情况

1.root 为空, attachToRoot = false

返回我们要加载的View,但是在xml中为其指定的LayoutParams将失效。

2.root 为空 attachToRoot = true;

同上

3.root 不为空 attachToRoot =  true

View的params存在,但返回添加了View的root

4.root 不为空 attachToRoot = false;

View的params存在 返回View