LayoutInflater源碼分析

LayoutInflater

開頭先附一段LayoutInflater類的注釋簡介

/**
 * Instantiates a layout XML file into its corresponding {@link android.view.View}
 * objects. It is never used directly. Instead, use
 * {@link android.app.Activity#getLayoutInflater()} or
 * {@link Context#getSystemService} 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.
 *
 * To create a new LayoutInflater with an additional {@link Factory} for your
 * own views, you can use {@link #cloneInContext} to clone an existing
 * ViewFactory, and then call {@link #setFactory} on it to include your
 * Factory.
 *
 * For performance reasons, view inflation relies heavily on pre-processing of
 * XML files that is done at build time. Therefore, it is not currently possible
 * to use LayoutInflater with an XmlPullParser over a plain XML file at runtime;
 * it only works with an XmlPullParser returned from a compiled resource
 * (R.<em>something</em> file.)
 */

這是LayoutInflater開頭的一段介紹,我們能看到幾個重要的信息:

  1. LayoutInfalter的作用是把XML轉(zhuǎn)化成對應(yīng)的View對象灭翔,需要用Activity#getLayoutInflater()或者getSystemService獲取谚中,會綁定當(dāng)前的Context
  2. 如果需要使用自定義的Factory查看替換加載信息,需要用cloneInContext去克隆一個ViewFactory囱嫩,然后調(diào)用setFactory設(shè)置自定義的Factory
  3. 性能原因,inflate會在build階段進行,無法用來加載一個外部文本XML文件破喻,只能加載R.xxx.xxx這種處理好的資源文件。
//LayoutInflater.java
    public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
    //root是否為null來決定attachToRoot是否為true盟榴。
        return inflate(resource, root, root != null);
    }
    public View inflate(XmlPullParser parser, @Nullable ViewGroup root) {
        return inflate(parser, root, root != null);
    }
    public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
        final Resources res = getContext().getResources();
        ...

        final XmlResourceParser parser = res.getLayout(resource);
        try {
            return inflate(parser, root, attachToRoot);
        } finally {
            parser.close();
        }
    }
//三個inflate方法最終都會調(diào)用到下面這個三個參數(shù)的inflate方法曹质。
    /**
     * parser XML節(jié)點包含了View的層級描述
     * root 需要attached到的根目錄,如果attachToRoot為true則root必須不為null。
     * attachToRoot 加載的層級是否需要attach到rootView羽德,
     * return attachToRoot為true几莽,就返回root,反之false就返回加載的XML文件的根節(jié)點View宅静。
     */
    public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
        synchronized (mConstructorArgs) {

            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)) {
                    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
                    final View temp = createViewFromTag(root, name, inflaterContext, attrs);
                    ViewGroup.LayoutParams params = null;
                    if (root != null) {
                        // Create layout params that match root, if supplied
                        params = root.generateLayoutParams(attrs);
                        if (!attachToRoot) {
                            // Set the layout params for temp if we are not
                            // attaching. (If we are, we use addView, below)
                            temp.setLayoutParams(params);
                        }
                    }

                    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.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解析XML文件章蚣,并根據(jù)得到的標(biāo)簽名執(zhí)行不同的邏輯:
1、首先如果是merge標(biāo)簽姨夹,會走rInflate方法纤垂,方法前面帶r的說明是recurse遞歸方法
2、如果不是merge標(biāo)簽磷账,執(zhí)行createViewFromTag峭沦,根據(jù)傳入的nameattrs獲取到name對應(yīng)的rootView并且添加到root里面。

針對merge標(biāo)簽逃糟,如果是merge標(biāo)簽必須有root并且必須attachToRoot==true吼鱼,否則直接拋異常,所以我們得知merge必須作為root標(biāo)簽使用履磨,并且不能用在子標(biāo)簽中①蛉抓,rInflate方法中也會針對merge標(biāo)簽進行檢查,保證merge標(biāo)簽不會出現(xiàn)在子標(biāo)簽中剃诅,后面會有介紹巷送。
檢查通過則調(diào)用rInflate(parser, root, inflaterContext, attrs, false)方法,遞歸遍歷root的層級矛辕,解析加載childrenView掛載到parentView下面笑跛,rinflate詳細解析可以看rinflate

如果不是merge標(biāo)簽則調(diào)用createViewFromTag(root, name, inflaterContext, attrs)聊品,這個方法的作用是加載名字為name的view飞蹂,根據(jù)name反射方式創(chuàng)建對應(yīng)的View,根據(jù)傳入的attrs構(gòu)造Params設(shè)置給View翻屈,返回創(chuàng)建好的View陈哑。
當(dāng)然這只是創(chuàng)建了一個View,需要再調(diào)用rInflateChildren(parser, temp, attrs, true)伸眶,這個方法也是一個遞歸方法惊窖,它的作用是根據(jù)傳入的parser包含的層級,加載此層級的子View并掛載到temp下面厘贼。

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.
        // 如果傳入的attr中包含theme屬性界酒,則使用此attr中的theme。
        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) {
                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 (Exception e) {
            ...
        }
    }

先看當(dāng)前標(biāo)簽的attr屬性里面是否設(shè)置了theme嘴秸,如果設(shè)置了就用當(dāng)前標(biāo)簽的theme屬性毁欣,綁定到context上面庇谆。
這里很有意思的是特殊判斷了一個TAG_1995,也就是blink凭疮,一個將包裹的內(nèi)容每隔500ms顯示隱藏的一個標(biāo)簽饭耳,怎么看都像個彩蛋~
然后調(diào)用mFactory2onCreateView,如果沒有設(shè)置mFactory2就嘗試mFactory,否則調(diào)用mPrivateFactory,mFactory2和mFactory后面再說哭尝,這里先往后走哥攘。
如果還是沒有加載到view,先判斷name材鹦,看名字里是不是有.逝淹,如果沒有就表明是Android原生的View,最終都會調(diào)用到createView方法桶唐,onCreateView最終會調(diào)用到createView(name, "android.view.", attrs);栅葡,會在View名字天面添加"android.view."前綴。

下面是默認(rèn)的createView的實現(xiàn):

    @Nullable
    public final View createView(@NonNull Context viewContext, @NonNull String name,
            @Nullable String prefix, @Nullable AttributeSet attrs)
            throws ClassNotFoundException, InflateException {
        Objects.requireNonNull(viewContext);
        Objects.requireNonNull(name);
        Constructor<? extends View> constructor = sConstructorMap.get(name);
        if (constructor != null && !verifyClassLoader(constructor)) {
            constructor = null;
            sConstructorMap.remove(name);
        }
        Class<? extends View> clazz = null;

        try {
            if (constructor == null) {
                // Class not found in the cache, see if it's real, and try to add it
                clazz = Class.forName(prefix != null ? (prefix + name) : name, false,
                        mContext.getClassLoader()).asSubclass(View.class);

                if (mFilter != null && clazz != null) {
                    boolean allowed = mFilter.onLoadClass(clazz);
                    if (!allowed) {
                        failNotAllowed(name, prefix, viewContext, attrs);
                    }
                }
                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 = Class.forName(prefix != null ? (prefix + name) : name, false,
                                mContext.getClassLoader()).asSubclass(View.class);

                        boolean allowed = clazz != null && mFilter.onLoadClass(clazz);
                        mFilterMap.put(name, allowed);
                        if (!allowed) {
                            failNotAllowed(name, prefix, viewContext, attrs);
                        }
                    } else if (allowedState.equals(Boolean.FALSE)) {
                        failNotAllowed(name, prefix, viewContext, attrs);
                    }
                }
            }

            Object lastContext = mConstructorArgs[0];
            mConstructorArgs[0] = viewContext;
            Object[] args = mConstructorArgs;
            args[1] = attrs;

            try {
                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;
            } finally {
                mConstructorArgs[0] = lastContext;
            }
        } catch (Exception e) {
            ...
        } finally {
            Trace.traceEnd(Trace.TRACE_TAG_VIEW);
        }
    }

這個方法可以看到View是怎么創(chuàng)建出來的尤泽,用類的全限定名拿到class信息欣簇,有一個sConstructorMap緩存類的constructor,如果能拿到有效的構(gòu)造器就不再重復(fù)創(chuàng)建來提升效率坯约,如果沒有緩存的構(gòu)造器熊咽,就反射得到構(gòu)造器并添加到sConstructorMap中以便后面使用。這里有個mFilter來提供自定義選項闹丐,用戶可以自定義哪些類不允許構(gòu)造横殴。
拿到構(gòu)造器之后,實際上newInstance是調(diào)用了兩View個參數(shù)的構(gòu)造方法卿拴。第一個參數(shù)是Context衫仑,第二個參數(shù)是attrs,這樣我們就得到了需要加載的View堕花。

這里可以結(jié)合LayoutInflater.Factory2一起來看文狱,Activity實際上是實現(xiàn)了LayoutInflater.Factory2接口的:

//Activity.java
    public View onCreateView(@NonNull String name, @NonNull Context context,
            @NonNull AttributeSet attrs) {
        return null;
    }

所以我們可以直接在Activity里面重寫onCreateView方法,這樣就可以根據(jù)View的名字來實現(xiàn)我們的一些操作缘挽,比如換膚的操作瞄崇,比如定義一個名字來表示某種自定義View『韭可以看這樣一個用法:

    <PlaceHolder
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="include LinearLayout"
        android:textColor="#fff"
        android:textSize="15sp" />

然后我們在重寫的onCreateView里面判斷name:

    @Override
    public View onCreateView(String name, Context context, AttributeSet attrs) {
        if ("PlaceHolder".equals(name)) {
            return new TextView(this, attrs);
        }
        return super.onCreateView(name, context, attrs);
    }

這樣其實就不拘泥于名字可以自己創(chuàng)建對應(yīng)的View杠袱,這樣其實可以用在多個module依賴的時候,如果在moduleA中得不到moduleB的某個自定義View窝稿,可以使用一個這樣的方式來在moudleA中暫時的用來做一個占位標(biāo)記,在moduleB中做一個判斷凿掂。
同樣的伴榔,通過上面的代碼我們知道LayoutInflater是通過反射拿到構(gòu)造方法來創(chuàng)建View的纹蝴,那眾所周知反射是有性能損耗的,那么我們可以在onCreateView方法中判斷名字直接new出來踪少,當(dāng)然也可以跟AppcompatActivity里面做的一樣塘安,做一些兼容的操作來替換成不同版本的View:

public final View createView(View parent, final String name, @NonNull Context context,
        View view = null;
        switch (name) {
            case "TextView":
                view = new AppCompatTextView(context, attrs);
                break;
            case "ImageView":
                view = new AppCompatImageView(context, attrs);
                break;
            case "Button":
                view = new AppCompatButton(context, attrs);
                break;
            case "EditText":
                view = new AppCompatEditText(context, attrs);
                break;
            case "Spinner":
                view = new AppCompatSpinner(context, attrs);
                break;
            case "ImageButton":
                view = new AppCompatImageButton(context, attrs);
                break;
            ...
        }
...
        return view;
    }

還沒有展開說rinflate,篇幅限制援奢,放到另外一篇文章中去分析兼犯,rinflate源碼分析
流程圖如下:

流程圖

總結(jié):
  1. LayoutInfalter的作用是把XML轉(zhuǎn)化成對應(yīng)的View對象集漾,需要用Activity#getLayoutInflater()或者getSystemService獲取
  2. 加載時先判斷是否是merge標(biāo)簽切黔,merge標(biāo)簽走遞歸方法rinflate,否則走createViewFromTag
  3. createViewFromTag作用是根據(jù)xml標(biāo)簽的名字去加載對應(yīng)的View具篇,使用的是反射的方法
  4. LayoutInflater.Factory2是設(shè)計出來靈活構(gòu)造View的接口纬霞,可以用來實現(xiàn)換膚或者替換View的功能,同時也是AppcompatActivity用來做兼容和版本替換的接口
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末驱显,一起剝皮案震驚了整個濱河市诗芜,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌埃疫,老刑警劉巖伏恐,帶你破解...
    沈念sama閱讀 218,122評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異栓霜,居然都是意外死亡翠桦,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,070評論 3 395
  • 文/潘曉璐 我一進店門叙淌,熙熙樓的掌柜王于貴愁眉苦臉地迎上來秤掌,“玉大人,你說我怎么就攤上這事鹰霍∥偶” “怎么了?”我有些...
    開封第一講書人閱讀 164,491評論 0 354
  • 文/不壞的土叔 我叫張陵茂洒,是天一觀的道長孟岛。 經(jīng)常有香客問我,道長督勺,這世上最難降的妖魔是什么渠羞? 我笑而不...
    開封第一講書人閱讀 58,636評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮智哀,結(jié)果婚禮上次询,老公的妹妹穿的比我還像新娘。我一直安慰自己瓷叫,他們只是感情好屯吊,可當(dāng)我...
    茶點故事閱讀 67,676評論 6 392
  • 文/花漫 我一把揭開白布送巡。 她就那樣靜靜地躺著,像睡著了一般盒卸。 火紅的嫁衣襯著肌膚如雪骗爆。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,541評論 1 305
  • 那天蔽介,我揣著相機與錄音摘投,去河邊找鬼。 笑死虹蓄,一個胖子當(dāng)著我的面吹牛犀呼,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播武花,決...
    沈念sama閱讀 40,292評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼圆凰,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了体箕?” 一聲冷哼從身側(cè)響起专钉,我...
    開封第一講書人閱讀 39,211評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎累铅,沒想到半個月后跃须,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,655評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡娃兽,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,846評論 3 336
  • 正文 我和宋清朗相戀三年菇民,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片投储。...
    茶點故事閱讀 39,965評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡第练,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出玛荞,到底是詐尸還是另有隱情娇掏,我是刑警寧澤,帶...
    沈念sama閱讀 35,684評論 5 347
  • 正文 年R本政府宣布勋眯,位于F島的核電站婴梧,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏客蹋。R本人自食惡果不足惜塞蹭,卻給世界環(huán)境...
    茶點故事閱讀 41,295評論 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望讶坯。 院中可真熱鬧番电,春花似錦、人聲如沸辆琅。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,894評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至洼冻,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間隅很,已是汗流浹背撞牢。 一陣腳步聲響...
    開封第一講書人閱讀 33,012評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留叔营,地道東北人屋彪。 一個月前我還...
    沈念sama閱讀 48,126評論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像绒尊,于是被迫代替她去往敵國和親畜挥。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,914評論 2 355