Android LayoutInflater 源碼解析

在上篇文章中我們學(xué)習(xí)了setContentView的源碼,還記得其中的LayoutInflater嗎?本篇文章就來(lái)學(xué)習(xí)下LayoutInflater。

    @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。

1、LayoutInflater 簡(jiǎn)介

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.

翻譯過(guò)來(lái)就是:LayoutInflater 的作用就是將XML布局文件實(shí)例化為相應(yīng)的 View 對(duì)象,需要通過(guò)Activity.getLayoutInflater() 或 Context.getSystemService(Class) 來(lái)獲取與當(dāng)前Context已經(jīng)關(guān)聯(lián)且正確配置的標(biāo)準(zhǔn)LayoutInflater。

總共有三種方法來(lái)獲取 LayoutInflater:

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

事實(shí)上,這三種方法之間是有關(guān)聯(lián)的:

  • Activity.getLayoutInflater() 最終會(huì)調(diào)用到 PhoneWindow 的構(gòu)造方法,實(shí)際上最終調(diào)用的就是方法三;
  • 而方法三最終會(huì)調(diào)用到方法二 Context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) ;

2、inflate 方法解析

image

LayoutInflater 的 inflate 方法總共有四個(gè),屬于重載的關(guān)系,最終都會(huì)調(diào)用到 inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) 方法。

備注:以下源碼中有七條備注。

    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;
                // ① 尋找布局的根節(jié)點(diǎn),判斷布局的合理性
                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標(biāo)簽,則必須依附于一個(gè)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
                    // ③ 根據(jù)節(jié)點(diǎn)名來(lái)創(chuàng)建View對(duì)象 
                    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
                        // ④ 如果設(shè)置的Root不為null,則根據(jù)當(dāng)前標(biāo)簽的參數(shù)生成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 ,則對(duì)這個(gè)Tag和創(chuàng)建出來(lái)的View設(shè)置LayoutParams;注意:此處的params只有當(dāng)被添加到一個(gè)Viewz中的時(shí)候才會(huì)生效;
                            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,則添加創(chuàng)建出來(lái)的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;
        }
    }

備注:根據(jù)以上源碼,我們也可以分析出來(lái) inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) 不同參數(shù)值帶來(lái)的影響:

  1. 如果root為null,attachToRoot將失去作用,設(shè)置任何值都沒(méi)有意義;
  2. 如果root不為null,attachToRoot設(shè)為true,則會(huì)給加載的布局文件的指定一個(gè)父布局,即root;
  3. 如果root不為null,attachToRoot設(shè)為false,則會(huì)將布局文件最外層的所有l(wèi)ayout屬性進(jìn)行設(shè)置,當(dāng)該view被添加到父view當(dāng)中時(shí),這些layout屬性會(huì)自動(dòng)生效;
  4. 在不設(shè)置attachToRoot參數(shù)的情況下,如果root不為null,attachToRoot參數(shù)默認(rèn)為true;

3、rInflate 方法解析

以上代碼中我們還有兩個(gè)方法沒(méi)有分析:rInflate 和 rInflateChildren ;而 rInflateChildren 實(shí)際上是調(diào)用了rInflate;

備注:以下源碼中有六條備注。

    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) {
                // ① 如果這里出現(xiàn)了include標(biāo)簽,就會(huì)拋出異常
                    throw new InflateException("<include /> cannot be the root element");
                }
                parseInclude(parser, context, parent, attrs);
            } else if (TAG_MERGE.equals(name)) {                
                // ② 同理如果這里出現(xiàn)了merge標(biāo)簽,也會(huì)拋出異常
                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);
                // ④如果當(dāng)前View是ViewGroup(包裹了別的View)則在此處inflate其所有的子View
                rInflateChildren(parser, view, attrs, true);
                // ⑤添加inflate出來(lái)的view到parent中
                viewGroup.addView(view, params);
            }
        }
        if (pendingRequestFocus) {
            parent.restoreDefaultFocus();
        }
        if (finishInflate) {
            // ⑥如果inflate結(jié)束,則回調(diào)parent的onFinishInflate方法
            parent.onFinishInflate();
        }
    }

總結(jié):

  • 首先進(jìn)行View的合理性校驗(yàn),include、merge等標(biāo)簽;
  • 通過(guò) createViewFromTag 創(chuàng)建出 View 對(duì)象;
  • 如果是 ViewGroup,則重復(fù)以上步驟;
  • add View 到相應(yīng)的 parent 中;

4、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,則調(diào)用mFactory2的onCreateView方法
                view = mFactory2.onCreateView(parent, name, context, attrs);
            } else if (mFactory != null) {
                // ② 有mFactory,則調(diào)用mFactory的onCreateView方法
                view = mFactory.onCreateView(name, context, attrs);
            } else {
                view = null;
            }
            if (view == null && mPrivateFactory != null) {
                // ③ 有mPrivateFactory,則調(diào)用mPrivateFactory的onCreateView方法
                view = mPrivateFactory.onCreateView(parent, name, context, attrs);
            }
            if (view == null) {
                // ④ 走到這步說(shuō)明三個(gè)Factory都沒(méi)有,則開(kāi)始自己創(chuàng)建View
                final Object lastContext = mConstructorArgs[0];
                mConstructorArgs[0] = context;
                try {
                    if (-1 == name.indexOf('.')) {
                        // ⑤ 如果View的name中不包含 '.' 則說(shuō)明是系統(tǒng)控件,會(huì)在接下來(lái)的調(diào)用鏈在name前面加上 'android.view.'
                        view = onCreateView(parent, name, attrs);
                    } else {
                        // ⑥ 如果name中包含 '.' 則直接調(diào)用createView方法,onCreateView 后續(xù)也是調(diào)用了createView
                        view = createView(name, null, attrs);
                    }
                } finally {
                    mConstructorArgs[0] = lastContext;
                }
            }
            return view;
        } catch (InflateException e) {
            throw e;
        } 
    }

總結(jié):

  • createViewFromTag 方法比較簡(jiǎn)單,首先嘗試通過(guò) Factory 來(lái)創(chuàng)建View;
  • 如果沒(méi)有 Factory 的話則通過(guò) createView 來(lái)創(chuàng)建View;

5、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);
                    }
                }
                // ① 反射獲取這個(gè)View的構(gòu)造器
                constructor = clazz.getConstructor(mConstructorSignature);
                constructor.setAccessible(true);
                // ② 緩存構(gòu)造器
                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;
            // ③ 使用反射創(chuàng)建 View 對(duì)象,這樣一個(gè) View 就被創(chuàng)建出來(lái)了
            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) {
        } 
    }

總結(jié):

  • createView 方法也比較簡(jiǎn)單,通過(guò)反射來(lái)創(chuàng)建的 View 對(duì)象;

6、總結(jié)

通過(guò)本文我們學(xué)習(xí)到 LayoutInflater 創(chuàng)建 View的過(guò)程,也知道了 inflate 方法不同參數(shù)的意義,以及開(kāi)發(fā)中遇到的一些異常在源碼中的根源??梢钥吹綇牟季种?inflate 一個(gè)個(gè)具體的 View 的過(guò)程其實(shí)也很簡(jiǎn)單:

  • 通過(guò) XML 的 Pull 解析方式獲取 View 的標(biāo)簽;
  • 通過(guò)標(biāo)簽以反射的方式來(lái)創(chuàng)建 View 對(duì)象;
  • 如果是 ViewGroup 的話則會(huì)對(duì)子 View 遍歷并重復(fù)以上步驟,然后 add 到父 View 中;
  • 與之相關(guān)的幾個(gè)方法:inflate ——》 rInflate ——》 createViewFromTag ——》 createView ;

參考

歡迎關(guān)注
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容