LayoutInflater中inflate過程全解析

LayoutInflater類中的inflate方法是咱們經常使用的一個工具,無論是自定義view仍是ListView這類adapter類中,inflate方法都能幫助咱們生成咱們須要的view。那麼inflate的原理是什麼呢?下面就來分析下源碼。java

inflate方法有幾個重載的方法,可是最後都是調用到了其中的一個方法,也就是View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) ,那麼咱們就從這個方法開始往下看。node

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);
            //1. 保留上一次的context對象
            Context lastContext = (Context) mConstructorArgs[0];
            //2.存儲當前inflate的context對象
            mConstructorArgs[0] = inflaterContext;
            View result = root;

            try {
                // Look for the root node.
                int type;
                //3.找到第一個START_TAG
                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();
                
                ...
                   //4.處理merge標籤
                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
                    //5.建立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
                        //6.獲取root中默認的layoutParams
                        params = root.generateLayoutParams(attrs);
                        //7.若是不須要add到root中
                        if (!attachToRoot) {
                            // Set the layout params for temp if we are not
                            // attaching. (If we are, we use addView, below)
                            temp.setLayoutParams(params);
                        }
                    }
                      ...
                    // Inflate all children under temp against its context.
                    //8.處理其餘的子view
                    rInflateChildren(parser, temp, attrs, true);
                      ...
                    // We are supposed to attach all the views we found (int temp)
                    // to root. Do that now.
                    if (root != null && attachToRoot) {
                        //9.addview到rootview中去
                        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 (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處,用到了一個成員變量mConstructorArgs,這是一個大小爲2的數組,用來存儲view構造中須要用到兩個對象:context和attributeSet.在代碼3處,經過一個while循環處理,找到xml中的第一個start_tag,也就是咱們定義的root view。在代碼4處,這裏主要用來處理xml定義的<merge>標籤,這裏不做贅述。在代碼5處,經過createViewFromTag方法建立了view,也就是咱們剛剛處理的start_tag中的view,因此真正的建立是在這個方法中,咱們來看下這個方法。android

View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,
            boolean ignoreThemeAttr) {
       //1.處理view標籤
        if (name.equals("view")) {
            name = attrs.getAttributeValue(null, "class");
        }

        // Apply a theme wrapper, if allowed and one is specified.
        //2.若是指定了Theme屬性,用ContextThemeWrapper包裝一下
        if (!ignoreThemeAttr) {
            final TypedArray ta = context.obtainStyledAttributes(attrs, ATTRS_THEME);
            final int themeResId = ta.getResourceId(0, 0);
            if (themeResId != 0) {
                context = new ContextThemeWrapper(context, themeResId);
            }
            ta.recycle();
        }
        //3.處理blink標籤
        if (name.equals(TAG_1995)) {
            // Let's party like it's 1995!
            return new BlinkLayout(context, attrs);
        }

        try {
            //4.mFactory,mFactory2提供了一種便捷操做讓咱們能夠本身定製view
            View view;
            if (mFactory2 != null) {
                view = mFactory2.onCreateView(parent, name, context, attrs);
            } else if (mFactory != null) {
                view = mFactory.onCreateView(name, context, attrs);
            } else {
                view = null;
            }

            if (view == null && mPrivateFactory != null) {
                view = mPrivateFactory.onCreateView(parent, name, context, attrs);
            }

            if (view == null) {
                //5.若是沒有指定上面的factory信息,那麼久調用下面的機制建立view
                final Object lastContext = mConstructorArgs[0];
                mConstructorArgs[0] = context;
                try {
                    //6.系統view
                    if (-1 == name.indexOf('.')) {
                        view = onCreateView(parent, name, attrs);
                    } else {
                        //7.自定義的view
                        view = createView(name, null, attrs);
                    }
                } finally {
                    mConstructorArgs[0] = lastContext;
                }
            }

            return view;
        } catch (InflateException e) {
            throw e;

        } catch (ClassNotFoundException e) {
            final InflateException ie = new InflateException(attrs.getPositionDescription()
                    + ": Error inflating class " + name);
            ie.initCause(e);
            throw ie;

        } catch (Exception e) {
            final InflateException ie = new InflateException(attrs.getPositionDescription()
                    + ": Error inflating class " + name);
            ie.initCause(e);
            throw ie;
        }
    }

代碼1處,用來處理咱們在xml中定義的<view class="">標籤,獲取view的類名。在代碼2處,若是xml中有定義theme,須要用定義的Theme來wrapper一下context,生成一個新的ContextThemeWrapper。代碼3處用來處理<Blink>標籤,它是一種閃爍的佈局處理,不細究。在代碼4處,有多個Factory,這個幾個Factory的做用是LayoutInflater爲咱們提供了一些工廠方法,讓咱們本身去createView,默認都是沒有這些Factory方法。從代碼5處開始就是LayoutInflate的內部建立view的過程。首先保存一下context,而後判斷咱們的view的name中是否有.,也就是判斷是不是自定義的view仍是系統中的view,咱們只看系統view的建立方法,也就是從代碼6處開始往下看,調用onCreateView方法.數組

protected View onCreateView(String name, AttributeSet attrs)
            throws ClassNotFoundException {
        return createView(name, "android.view.", attrs);
    }


    public final View createView(String name, String prefix, AttributeSet attrs)
            throws ClassNotFoundException, InflateException {
        //1.檢查map緩存中是否有緩存的構造器
        Constructor<? extends View> constructor = sConstructorMap.get(name);
        Class<? extends View> clazz = null;

        try {
            Trace.traceBegin(Trace.TRACE_TAG_VIEW, name);

            if (constructor == null) {
                // Class not found in the cache, see if it's real, and try to add it
               //2.獲取name表示的Class對象
                clazz = mContext.getClassLoader().loadClass(
                        prefix != null ? (prefix + name) : name).asSubclass(View.class);
                //3.filter過濾class對象
                if (mFilter != null && clazz != null) {
                    boolean allowed = mFilter.onLoadClass(clazz);
                    if (!allowed) {
                        failNotAllowed(name, prefix, attrs);
                    }
                }
                //4.獲取構造器
                constructor = clazz.getConstructor(mConstructorSignature);
                constructor.setAccessible(true);
                //5.緩存構造器
                sConstructorMap.put(name, constructor);
            } else {
                // If we have a filter, apply it to cached constructor
                if (mFilter != null) {
                    // Have we seen this name before?
                    Boolean allowedState = mFilterMap.get(name);
                    if (allowedState == null) {
                        // New class -- remember whether it is allowed
                        clazz = mContext.getClassLoader().loadClass(
                                prefix != null ? (prefix + name) : name).asSubclass(View.class);
                        
                        boolean allowed = clazz != null && mFilter.onLoadClass(clazz);
                        mFilterMap.put(name, allowed);
                        if (!allowed) {
                            failNotAllowed(name, prefix, attrs);
                        }
                    } else if (allowedState.equals(Boolean.FALSE)) {
                        failNotAllowed(name, prefix, attrs);
                    }
                }
            }
            //6.args實參,第一個參數是context
            Object[] args = mConstructorArgs;
            args[1] = attrs;
           //7.反射獲取view,調用的就是new View(Context,AttributeSet)
            final View view = constructor.newInstance(args);
            if (view instanceof ViewStub) {
                // Use the same context when inflating ViewStub later.
                final ViewStub viewStub = (ViewStub) view;
                viewStub.setLayoutInflater(cloneInContext((Context) args[0]));
            }
            return view;

        } catch (NoSuchMethodException e) {
            InflateException ie = new InflateException(attrs.getPositionDescription()
                    + ": Error inflating class "
                    + (prefix != null ? (prefix + name) : name));
            ie.initCause(e);
            throw ie;

        } 
        ...
    }

代碼1處檢查sConstructorMap中是否有當前view的緩存的構造器,第一次處理的時候都沒有,往下繼續看。代碼2處,使用反射,直接獲得了一個view的Class對象,而後使用mFilter檢查這個class對象是不是咱們容許建立的Class對象,默認這個filter是不做過濾的。代碼4處,經過這個class對象建立一個Constructor構造器對象,從mConstructorSignature這個對象上能夠看出,使用的是public View(Context, AttributeSet)這個構造器。代碼5處用來緩存這個構造器對象。代碼6處用來傳參,第一個參數是context已經在以前的方法中設置過,args[1]傳遞attributeSet對象。代碼7處使用反射直接生成了View,這樣最後就生成了咱們須要View對象了。緩存

回到inflate方法中,createViewFromTag已經建立了咱們指定的view,接着往下看。代碼六、7中,若是提供了inflate方法中第二個參數ViewGroup的話,會獲取這個ViewGroup中的layoutParams,而且將它設置給剛剛生成出來的View上。處理完這些以後也就是晶晶處理了最開始的rootView,其餘的子節點的view尚未處理。因此在代碼8處,就是處理接下來的子view。咱們大體看一下代碼.app

final void rInflateChildren(XmlPullParser parser, View parent, AttributeSet attrs,
            boolean finishInflate) throws XmlPullParserException, IOException {
        rInflate(parser, parent, parent.getContext(), attrs, finishInflate);
    }

    void rInflate(XmlPullParser parser, View parent, Context context,
            AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException {

        final int depth = parser.getDepth();
        int type;

        while (((type = parser.next()) != XmlPullParser.END_TAG ||
                parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {

            if (type != XmlPullParser.START_TAG) {
                continue;
            }

            final String name = parser.getName();
            
            if (TAG_REQUEST_FOCUS.equals(name)) {
                parseRequestFocus(parser, parent);
            } else if (TAG_TAG.equals(name)) {
                parseViewTag(parser, parent, attrs);
            } else if (TAG_INCLUDE.equals(name)) {
                if (parser.getDepth() == 0) {
                    throw new InflateException("<include /> cannot be the root element");
                }
                parseInclude(parser, context, parent, attrs);
            } else if (TAG_MERGE.equals(name)) {
                throw new InflateException("<merge /> must be the root element");
            } else {
                final View view = createViewFromTag(parent, name, context, attrs);
                final ViewGroup viewGroup = (ViewGroup) parent;
                final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
                rInflateChildren(parser, view, attrs, true);
                viewGroup.addView(view, params);
            }
        }

        if (finishInflate) {
            parent.onFinishInflate();
        }
    }

大體看一下,仍是同樣的配方,使用createViewFromTag建立接下來的每一個子View,因此不細究了。ide

最後在inflate方法中還須要判斷是否須要將當前建立的view 加到第二個參數提供的ViewGroup中,這個判斷就是第三個參數提供的。大體的流程也就是這樣吧~~工具

相關文章
相關標籤/搜索