LayoutInflater源碼解析

LayoutInflater我們經常會用到,在列表適配器中或者在加載自定義布局時,它的作用就是將一個xml文件渲染成一個View或者ViewGroup,雖然知道它的作用的用法,但是弄清楚它的工作原理也是很有必要的,今天就通過解析它的源碼來分析下它的工作原理。

基本使用方法

首先還是來說說它的幾種用法:

LayoutInflater layoutInflater = getLayoutInflater();//如果是在Activity中,可以直接使用getLayoutInflater()方法

其他地方可以使用下面這兩種方式:

LayoutInflater layoutInflater = LayoutInflater.from(context);
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

其實from(context)這種方法實際上也就是第三種方式了。可以看LayoutInflater類內部的from方法:

public static LayoutInflater from(Context context) {
    LayoutInflater LayoutInflater =
            (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    if (LayoutInflater == null) {
        throw new AssertionError("LayoutInflater not found.");
    }
    return LayoutInflater;
}

我們再看看getLayoutInflater()方法的實現:

public LayoutInflater getLayoutInflater() {
    return getWindow().getLayoutInflater();
}

說明這里了是調用了Window類的getLayoutInflater()方法,而Window類只是一個抽象類,它的實現類其實是PhoneWindow,那就看看PhoneWindow類中getLayoutInflater()方法的實現:

public LayoutInflater getLayoutInflater() {
    return mLayoutInflater;
}

而在PhoneWindow的構造方法中可以看到:

public PhoneWindow(Context context) {
    super(context);
    mLayoutInflater = LayoutInflater.from(context);
}

所以說這三種方式從根本上說都是一樣的,通過Content的getSystemService方法,傳遞Context.LAYOUT_INFLATER_SERVICE參數,就能獲取到LayoutInflater對象了。實際上在getSystemService方法中獲取到的LayoutInflater對象其實是PhoneLayoutInflater這個子類對象,因為Context的包裝類ContextThemeWrapper中定義了getSystemService方法:

public Object getSystemService(String name) {
    if (LAYOUT_INFLATER_SERVICE.equals(name)) {
        if (mInflater == null) {
            mInflater = LayoutInflater.from(getBaseContext()).cloneInContext(this);
        }
        return mInflater;
    }
    return getBaseContext().getSystemService(name);
}

而LayoutInflater中的cloneInContext方法只是一個抽象方法,在PhoneLayoutInflater有關于這個方法的實現:

public LayoutInflater cloneInContext(Context newContext) {
    return new PhoneLayoutInflater(this, newContext);
}

以上是獲取LayoutInflater對象,接著是用LayoutInflater對象加載xml布局:

View view = layoutInflater.inflate(R.layout.activity_main, null);

另外inflate還有三個重載方法:

inflate(int resource,  ViewGroup root, boolean attachToRoot);

inflate(XmlPullParser parser, ViewGroup root);

inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot);

仔細看這幾個方法的關系,不難發現,使用xml資源id加載的方法最終會調用這個方法:

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) + ")");
    }

    final XmlResourceParser parser = res.getLayout(resource);
    try {
        return inflate(parser, root, attachToRoot);
    } finally {
        parser.close();
    }
}

先是獲取到系統的Resource對象,然后通過getLayout方法傳遞資源id獲取到一個XML解析器對象,最終會調用下面這個方法

inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot);

Android中的布局都是xml格式的,所以涉及到xml的解析,而解析xml有DOM、SAX和PULL這幾種方式,其中DOM不適合xml文檔較大,內存較小的場景,SAX和PULL都具有解析速度快,占用內存小的優點,但PULL操作更簡單,所以Android選擇了PULL方式來解析布局xml文件。

DOM,通用性強,它會將XML文件的所有內容讀取到內存中,然后允許您使用DOM API遍歷XML樹、檢索所需的數據;簡單直觀,但需要將文檔讀取到內存,并不太適合移動設備;SAX,SAX是一個解析速度快并且占用內存少的xml解析器;采用事件驅動,它并不需要解析整個文檔;實現:繼承DefaultHandler,覆寫startElement、endElement、characters等方法;PULL,Android自帶的XML解析器,和SAX基本類似,也是事件驅動,不同的是PULL事件返回的是數值型;推薦使用。

源碼解析

inflate方法的最終實現:

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了
        View result = root;

        try {
            // Look for the root node.
            
            //  首先會找到布局的根節點,如RelativeLayout、LinearLayout等
            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 (TAG_MERGE.equals(name)) {
                // 如果根節點是merge,那么它必須依附于root上,如果root為空或者依附屬性為false,就會拋出異常。
                if (root == null || !attachToRoot) {
                    throw new InflateException("<merge /> can be used only with a valid "
                            + "ViewGroup root and attachToRoot=true");
                }
                // 解析根節點下面的子節點,并創建對應的子View添加到根View中來
                rInflate(parser, root, inflaterContext, attrs, false);
            } else {
                // Temp is the root view that was found in the xml
                // 根節點不是merge,就根據root以及當前節點信息來生成一個根View
                final View temp = createViewFromTag(root, name, inflaterContext, attrs);

                ViewGroup.LayoutParams params = null;

                if (root != null) {
                    
                    // 如果指定了root,那么根據root的布局屬性生成一個LayoutParams
                    params = root.generateLayoutParams(attrs);
                    if (!attachToRoot) {
                        // 如果沒有指定加載的資源xml依附于root,那么把上面生成的LayoutParams設置給根View
                        temp.setLayoutParams(params);
                    }
                }

                // 開始解析加載子節點,并創建對應的子View添加到根View中來
                rInflateChildren(parser, temp, attrs, true);

                // 如果指定了root并且指定加載的xml依附于root,那么當整個資源xml解析完后就將根View添加到root中去
                if (root != null && attachToRoot) {
                    // 而且整個方法到這里就得到了要返回的結果了,因為一開始就把root賦值給result,最后返回的result仍然是添加了temp的root
                    root.addView(temp, params);
                }

                // 如果root為空且attachToRoot為false時,返回的就是根View
                if (root == null || !attachToRoot) {
                    result = temp;
                }
            }

        } catch (XmlPullParserException e) {
            final InflateException ie = new InflateException(e.getMessage(), e);
            ie.setStackTrace(EMPTY_STACK_TRACE);
            throw ie;
        } catch (Exception e) {
            final InflateException ie = new InflateException(parser.getPositionDescription()
                    + ": " + e.getMessage(), e);
            ie.setStackTrace(EMPTY_STACK_TRACE);
            throw ie;
        } finally {
            // Don't retain static reference on context.
            mConstructorArgs[0] = lastContext;
            mConstructorArgs[1] = null;

            Trace.traceEnd(Trace.TRACE_TAG_VIEW);
        }
        // 最后返回結果View
        return result;
    }
}

根據上面inflate()方法的源碼,總結一下幾點:

  • 當root為null時,attachToRoot的值已無關緊要,它會直接返回資源xml對應加載好的View。
  • 當root不為null、attachToRoot為false時,仍然會返回資源xml對應加載好的View,但是root的LayoutParams會被設置給返回的View。
  • 當root不為null、attachToRoot為true時,則會把資源xml對應的View添加到root中然后返回root。

接下來我們再看看是如何將xml生成對應的View的。

無論根節點是不是merge,最后都會調用rInflate()方法去解析加載子View,rInflateChildren()方法其實也是調用了rInflate(),所以看下rInflate()方法的源碼:

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();
    }
}

前面幾個條件判斷是解析幾個特殊的節點requestFocustagincludemerge,真正生成View并添加到父View中的是在最后一個else中。首先根據當前節點信息生成一個View,再遞歸這個View下所有子節點,最后將這個View添加到父View中,如果子節點都解析完了,就調用父View的onFinishInflate方法來結束解析。

通過上面的源碼可以看出,無論是temp還是每一個子View,都是通過createViewFromTag()方法生成的,下面我們就來一探究竟。

View createViewFromTag(View parent, String name, Context context, AttributeSet attrs, boolean ignoreThemeAttr) {

    ...

    try {
        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) {
            final Object lastContext = mConstructorArgs[0];
            mConstructorArgs[0] = context;
            try {
                if (-1 == name.indexOf('.')) {
                    view = onCreateView(parent, name, attrs);
                } else {
                    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, e);
        ie.setStackTrace(EMPTY_STACK_TRACE);
        throw ie;
    } catch (Exception e) {
        final InflateException ie = new InflateException(attrs.getPositionDescription() + ": Error inflating class " + name, e);
        ie.setStackTrace(EMPTY_STACK_TRACE);
        throw ie;
    }
}

如果mFactory2、mFactory、mPrivateFactory這幾個自定義工廠不為null時就調用他們的onCreateView方法來生成一個View,但從LayoutInflater的構造方法來看,這三個變量初始時都是空的,所以最終會調用LayoutInflater本身的onCreateView方法或者createView方法,其中if (-1 == name.indexOf('.'))這個判斷是xml中當前節點名中是否含有.,等于-1表示沒有,即代表系統的widget下的View,默認前綴是android.view.,最終他們都會調用createView(name, null, attrs)這個方法。

public final View createView(String name, String prefix, AttributeSet attrs) throws ClassNotFoundException, InflateException {
    Constructor<? extends View> constructor = sConstructorMap.get(name);
    // 先從緩存中找是否存在該節點對應View的構造方法
    if (constructor != null && !verifyClassLoader(constructor)) {
        constructor = null;
        sConstructorMap.remove(name);
    }
    Class<? extends View> clazz = null;

    try {
        if (constructor == null) {
            // 沒有就先根據類加載器通過全類名得到該類的反射類,再獲取其構造方法
            clazz = mContext.getClassLoader().loadClass(
                    prefix != null ? (prefix + name) : name).asSubclass(View.class);
            
            if (mFilter != null && clazz != null) {
                boolean allowed = mFilter.onLoadClass(clazz);
                if (!allowed) {
                    failNotAllowed(name, prefix, attrs);
                }
            }
            constructor = clazz.getConstructor(mConstructorSignature);
            constructor.setAccessible(true);
            sConstructorMap.put(name, constructor);
        } else {
            if (mFilter != null) {
                Boolean allowedState = mFilterMap.get(name);
                if (allowedState == null) {
                    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);
                }
            }
        }

        Object[] args = mConstructorArgs;
        args[1] = attrs;
        
        // 通過構造方法來生成對應的View
        final View view = constructor.newInstance(args);
        
        // 如果是ViewStub的情況
        if (view instanceof ViewStub) {
            final ViewStub viewStub = (ViewStub) view;
            viewStub.setLayoutInflater(cloneInContext((Context) args[0]));
        }
        return view;

    } 
    
    ...
    
}

LayoutInflater加載xml的原理

歸根到底就是通過XML解析器從根節點開始,遞歸解析xml的每個節點,通過當前節點名稱(全類名),使用ClassLoader獲取到對應類的構造方法,然后創建對應類的實例(View),最后將這個View添加到它的上層節點(父View)。并同時會解析對應xml節點的屬性作為View的屬性。每個層級的節點都會被生成一個個的View,并根據View的層級關系添加到對應的上層節點中去(直接父View),最終返回一個包含了所有解析好的子View的布局根View。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容