Android LayoutInflater 源碼解析

在上篇文章中咱們學習了setContentView的源碼,還記得其中的LayoutInflater嗎?本篇文章就來學習下LayoutInflater。node

@Override
    public void setContentView(int resId) {
        ensureSubDecor();
        ViewGroup contentParent = (ViewGroup) mSubDecor.findViewById(android.R.id.content);
        contentParent.removeAllViews();
        LayoutInflater.from(mContext).inflate(resId, contentParent);
        mOriginalWindowCallback.onContentChanged();
    }
複製代碼

備註:本文基於 Android 8.1.0。android

一、LayoutInflater 簡介

Instantiates a layout XML file into its corresponding View objects. It is never used directly. Instead, use Activity.getLayoutInflater() or Context.getSystemService(Class) to retrieve a standard LayoutInflater instance that is already hooked up to the current context and correctly configured for the device you are running on.緩存

翻譯過來就是:LayoutInflater 的做用就是將XML佈局文件實例化爲相應的 View 對象,須要經過Activity.getLayoutInflater() 或 Context.getSystemService(Class) 來獲取與當前Context已經關聯且正確配置的標準LayoutInflater。bash

總共有三種方法來獲取 LayoutInflater:微信

  1. Activity.getLayoutInflater();
  2. Context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) ;
  3. LayoutInflater.from(context);

事實上,這三種方法之間是有關聯的:app

  • Activity.getLayoutInflater() 最終會調用到 PhoneWindow 的構造方法,實際上最終調用的就是方法三;
  • 而方法三最終會調用到方法二 Context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) ;

二、inflate 方法解析

LayoutInflater 的 inflate 方法總共有四個,屬於重載的關係,最終都會調用到 inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) 方法。ide

備註:如下源碼中有七條備註。佈局

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;
            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 (TAG_MERGE.equals(name)) {
                // ② 若是是Merge標籤,則必須依附於一個RootView,不然拋出異常
                    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
                    // ③ 根據節點名來建立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不爲null,則根據當前標籤的參數生成LayoutParams
                        params = root.generateLayoutParams(attrs);
                        if (!attachToRoot) {
                            // Set the layout params for temp if we are not
                            // attaching. (If we are, we use addView, below)
                            // ⑤ 若是不是attachToRoot ,則對這個Tag和建立出來的View設置LayoutParams;注意:此處的params只有當被添加到一個Viewz中的時候纔會生效;
                            temp.setLayoutParams(params);
                        }
                    }
                    if (DEBUG) {
                        System.out.println("-----> start inflating children");
                    }
                    // Inflate all children under temp against its context.
                    // ⑥ inflate children tag
                    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) {
                        // ⑦ 若是Root不爲null且是attachToRoot,則添加建立出來的View到Root 中
                        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) {
                ......
            }
            return result;
        }
    }
複製代碼

備註:根據以上源碼,咱們也能夠分析出來 inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) 不一樣參數值帶來的影響:學習

  1. 若是root爲null,attachToRoot將失去做用,設置任何值都沒有意義;
  2. 若是root不爲null,attachToRoot設爲true,則會給加載的佈局文件的指定一個父佈局,即root;
  3. 若是root不爲null,attachToRoot設爲false,則會將佈局文件最外層的全部layout屬性進行設置,當該view被添加到父view當中時,這些layout屬性會自動生效;
  4. 在不設置attachToRoot參數的狀況下,若是root不爲null,attachToRoot參數默認爲true;

三、rInflate 方法解析

以上代碼中咱們還有兩個方法沒有分析:rInflate 和 rInflateChildren ;而 rInflateChildren 其實是調用了rInflate;ui

備註:如下源碼中有六條備註。

void rInflate(XmlPullParser parser, View parent, Context context,
            AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException {
        final int depth = parser.getDepth();
        int type;
        boolean pendingRequestFocus = false;
        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)) {
                pendingRequestFocus = true;
                consumeChildElements(parser);
            } else if (TAG_TAG.equals(name)) {
                parseViewTag(parser, parent, attrs);
            } else if (TAG_INCLUDE.equals(name)) {
                if (parser.getDepth() == 0) {
                // ① 若是這裏出現了include標籤,就會拋出異常
                    throw new InflateException("<include /> cannot be the root element");
                }
                parseInclude(parser, context, parent, attrs);
            } else if (TAG_MERGE.equals(name)) {                
                // ② 同理若是這裏出現了merge標籤,也會拋出異常
                throw new InflateException("<merge /> must be the root element");
            } else {
                // ③ 最重要的方法在這裏,createViewFromTag
                final View view = createViewFromTag(parent, name, context, attrs);
                final ViewGroup viewGroup = (ViewGroup) parent;
                final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
                // ④若是當前View是ViewGroup(包裹了別的View)則在此處inflate其全部的子View
                rInflateChildren(parser, view, attrs, true);
                // ⑤添加inflate出來的view到parent中
                viewGroup.addView(view, params);
            }
        }
        if (pendingRequestFocus) {
            parent.restoreDefaultFocus();
        }
        if (finishInflate) {
            // ⑥若是inflate結束,則回調parent的onFinishInflate方法
            parent.onFinishInflate();
        }
    }
複製代碼

總結:

  • 首先進行View的合理性校驗,include、merge等標籤;
  • 經過 createViewFromTag 建立出 View 對象;
  • 若是是 ViewGroup,則重複以上步驟;
  • add View 到相應的 parent 中;

四、createViewFromTag 方法解析

備註:如下源碼中有六條備註。

View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,
            boolean ignoreThemeAttr) {
        if (name.equals("view")) {
            name = attrs.getAttributeValue(null, "class");
        }
        // Apply a theme wrapper, if allowed and one is specified.
        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();
        }
        if (name.equals(TAG_1995)) {
            // Let's party like it's 1995!
            return new BlinkLayout(context, attrs);
        }
        try {
            View view;
            if (mFactory2 != null) {
                // ① 有mFactory2,則調用mFactory2的onCreateView方法
                view = mFactory2.onCreateView(parent, name, context, attrs);
            } else if (mFactory != null) {
                // ② 有mFactory,則調用mFactory的onCreateView方法
                view = mFactory.onCreateView(name, context, attrs);
            } else {
                view = null;
            }
            if (view == null && mPrivateFactory != null) {
                // ③ 有mPrivateFactory,則調用mPrivateFactory的onCreateView方法
                view = mPrivateFactory.onCreateView(parent, name, context, attrs);
            }
            if (view == null) {
                // ④ 走到這步說明三個Factory都沒有,則開始本身建立View
                final Object lastContext = mConstructorArgs[0];
                mConstructorArgs[0] = context;
                try {
                    if (-1 == name.indexOf('.')) {
                        // ⑤ 若是View的name中不包含 '.' 則說明是系統控件,會在接下來的調用鏈在name前面加上 'android.view.'
                        view = onCreateView(parent, name, attrs);
                    } else {
                        // ⑥ 若是name中包含 '.' 則直接調用createView方法,onCreateView 後續也是調用了createView
                        view = createView(name, null, attrs);
                    }
                } finally {
                    mConstructorArgs[0] = lastContext;
                }
            }
            return view;
        } catch (InflateException e) {
            throw e;
        } 
    }
複製代碼

總結:

  • createViewFromTag 方法比較簡單,首先嚐試經過 Factory 來建立View;
  • 若是沒有 Factory 的話則經過 createView 來建立View;

五、createView 方法解析

備註:如下源碼中有三條備註。

public final View createView(String name, String prefix, AttributeSet attrs)
            throws ClassNotFoundException, InflateException {
        Constructor<? extends View> constructor = sConstructorMap.get(name);
        if (constructor != null && !verifyClassLoader(constructor)) {
            constructor = null;
            sConstructorMap.remove(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 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); } } // ① 反射獲取這個View的構造器 constructor = clazz.getConstructor(mConstructorSignature); constructor.setAccessible(true); // ② 緩存構造器 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); } } } Object lastContext = mConstructorArgs[0]; if (mConstructorArgs[0] == null) { // Fill in the context if not already within inflation. mConstructorArgs[0] = mContext; } Object[] args = mConstructorArgs; args[1] = attrs; // ③ 使用反射建立 View 對象,這樣一個 View 就被建立出來了 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])); } mConstructorArgs[0] = lastContext; return view; } catch (ClassCastException e) { } } 複製代碼

總結:

  • createView 方法也比較簡單,經過反射來建立的 View 對象;

六、總結

經過本文咱們學習到 LayoutInflater 建立 View的過程,也知道了 inflate 方法不一樣參數的意義,以及開發中遇到的一些異常在源碼中的根源。能夠看到從佈局中 inflate 一個個具體的 View 的過程其實也很簡單:

  • 經過 XML 的 Pull 解析方式獲取 View 的標籤;
  • 經過標籤以反射的方式來建立 View 對象;
  • 若是是 ViewGroup 的話則會對子 View 遍歷並重復以上步驟,而後 add 到父 View 中;
  • 與之相關的幾個方法:inflate ——》 rInflate ——》 createViewFromTag ——》 createView ;

參考

廣告時間

今日頭條各Android客戶端團隊招人火爆進行中,各個級別和應屆實習生都須要,業務增加快、日活高、挑戰大、待遇給力,各位大佬走過路過千萬不要錯過!

本科以上學歷、非頻繁跳槽(如兩年兩跳),歡迎加個人微信詳聊:KOBE8242011

歡迎關注
相關文章
相關標籤/搜索