View的繪制流程 一、LayoutInflater.inflate詳解

今天的主題是LayoutInflate是怎樣獲取布局并將其添加到父控件中去的,閑話不多說直接切入正題绎晃。

一、LayoutInflate的創(chuàng)建

一般我們添加布局時調(diào)用的方法有這么幾種:

1帖旨、View.inflate(parent.getContext(), R.layout.item_layout, null);
2箕昭、LayoutInflater.from(context).inflate(R.layout.item_layout, parent);
3、LayoutInflater.from(context).inflate(R.layout.item_layout, parent解阅,false);
4落竹、getLayoutInflater().inflate(R.layout.item_layout, parent);
5、getLayoutInflater().inflate(R.layout.item_layout, parent货抄,false);

那么上面這些方法又有哪些區(qū)別呢述召,帶著在這個疑問我們來閱讀源碼吧。
首先是View.inflate(parent.getContext(), R.layout.item_layout, null);

public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
    LayoutInflater factory = LayoutInflater.from(context);
    return factory.inflate(resource, root);
}

View.inflate(parent.getContext(), R.layout.item_layout, null);方法最終會調(diào)用LayoutInflater.from(context)方法來獲得LayoutInflater對象蟹地。那我們來看看LayoutInflater.from(context);中做了哪些處理

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

這里我們看到LayoutInflater最終是通過context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);來創(chuàng)建的积暖。我們再看看Activity中的getLayoutInflater()對象是怎樣獲取LayoutInflater

@NonNull
public LayoutInflater getLayoutInflater() {
    return getWindow().getLayoutInflater();
}
@Override
public LayoutInflater getLayoutInflater() {
    return mLayoutInflater;
}

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

通過上面的代碼我們可以很清晰的看到在Activity中調(diào)用getLayoutInflate()方法會獲取PhoneWindow中的mLayoutInflater對象而mLayoutInflater對象實在PhoneWindow被創(chuàng)建的時候調(diào)用LayoutInflater.from(context);來賦值的。
根據(jù)之前的代碼我們看到不論通過哪種形式的調(diào)用最終是通過context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);方法來創(chuàng)建LayoutInflater對象的怪与。

二夺刑、inflate()

我們經(jīng)常用的inflate方法主要是有兩個,一個是兩個參數(shù)的另外一個是三個參數(shù)的分别,我們分別來看看他們的區(qū)別吧

public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
    return inflate(resource, root, root != null);
}

在上面源碼中我們看到兩個參數(shù)的inflate是調(diào)用三個參數(shù)的inflate方法遍愿,而第三個參數(shù)則傳入為父容器是否為空的布爾型參數(shù)下面我們通過源碼來分析一下這三個參數(shù)的作用

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

這個方法很簡單就是獲取資源布局使用XmlResourceParser進行保存。并調(diào)用inflate(XmlPullParser parser, @Nullable 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é)點并解析
            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 (DEBUG) {
                System.out.println("**************************");
                System.out.println("Creating root view: "
                        + name);
                System.out.println("**************************");
            }

            //這里判斷根節(jié)點是否為merge標簽如果是merge標簽并且沒有將資源文件往父容器添加的意圖就會跑出異常
            //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");
                }
                //遍歷子節(jié)點填充到父容器中沼填,直接返回父容器
                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;

                //如果存在父容器我們就根據(jù)attrs來設(shè)置View的參數(shù)
                if (root != null) {
                    if (DEBUG) {
                        System.out.println("Creating params from root: " +
                                root);
                    }
                    // 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);
                    }
                }

                if (DEBUG) {
                    System.out.println("-----> start inflating children");
                }

                // Inflate all children under temp against its context.
                //遍歷子節(jié)點將其填充到跟View中
                rInflateChildren(parser, temp, attrs, true);

                if (DEBUG) {
                    System.out.println("-----> done inflating children");
                }

                // We are supposed to attach all the views we found (int temp)
                // to root. Do that now.
                //如果滿足條件則將跟View添加到父容器中并返回父容器否則返回跟View
                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) {
            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);
        }
        return result;
    }
}

這一段代碼就比較有意思了首先告訴我們merge標簽不能獨立于父容器存在的,其次告訴我們?nèi)绻粋魅敫溉萜鲃t不會給根View設(shè)置寬高屬性括授,也就是說我們在xml文件中設(shè)置的layout_widthlayout_height都失去了作用坞笙。
我們再來看看rInflate:

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

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

    //遍歷子節(jié)點并創(chuàng)建Viwe添加到父容器中
    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();
    }
}

這段代碼很簡單主要是遍歷子節(jié)點創(chuàng)建對應(yīng)的View添加到parent中岩饼,其中對幾個特殊的標簽做了處理。其中merge標簽不能在非根節(jié)點而include標簽不能在根節(jié)點薛夜。到此我們的代碼就分析完了籍茧。


總結(jié):

  • LayoutInflate的創(chuàng)建最終是通過context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);來創(chuàng)建的。
  • inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot)方法的三個參數(shù)分別代表著子布局却邓,父容器硕糊,是否將子布局添加到父容器中。
  • 如果父容器不為空并且attachToRoot的值為true的時候腊徙,inflate方法會將子布局添加到父容器中并返回父容器的對象简十,否則返回子布局的View對象。
  • merge標簽只能在根節(jié)點使用而include標簽只能在非根節(jié)點使用撬腾。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末螟蝙,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子民傻,更是在濱河造成了極大的恐慌胰默,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,036評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件漓踢,死亡現(xiàn)場離奇詭異牵署,居然都是意外死亡,警方通過查閱死者的電腦和手機喧半,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,046評論 3 395
  • 文/潘曉璐 我一進店門奴迅,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人挺据,你說我怎么就攤上這事取具。” “怎么了扁耐?”我有些...
    開封第一講書人閱讀 164,411評論 0 354
  • 文/不壞的土叔 我叫張陵暇检,是天一觀的道長。 經(jīng)常有香客問我婉称,道長块仆,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,622評論 1 293
  • 正文 為了忘掉前任王暗,我火速辦了婚禮榨乎,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘瘫筐。我一直安慰自己,他們只是感情好铐姚,可當我...
    茶點故事閱讀 67,661評論 6 392
  • 文/花漫 我一把揭開白布策肝。 她就那樣靜靜地躺著肛捍,像睡著了一般。 火紅的嫁衣襯著肌膚如雪之众。 梳的紋絲不亂的頭發(fā)上拙毫,一...
    開封第一講書人閱讀 51,521評論 1 304
  • 那天,我揣著相機與錄音棺禾,去河邊找鬼缀蹄。 笑死,一個胖子當著我的面吹牛膘婶,可吹牛的內(nèi)容都是我干的缺前。 我是一名探鬼主播,決...
    沈念sama閱讀 40,288評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼悬襟,長吁一口氣:“原來是場噩夢啊……” “哼衅码!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起脊岳,我...
    開封第一講書人閱讀 39,200評論 0 276
  • 序言:老撾萬榮一對情侶失蹤逝段,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后割捅,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體奶躯,經(jīng)...
    沈念sama閱讀 45,644評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,837評論 3 336
  • 正文 我和宋清朗相戀三年亿驾,在試婚紗的時候發(fā)現(xiàn)自己被綠了嘹黔。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,953評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡颊乘,死狀恐怖参淹,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情乏悄,我是刑警寧澤浙值,帶...
    沈念sama閱讀 35,673評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站檩小,受9級特大地震影響开呐,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜规求,卻給世界環(huán)境...
    茶點故事閱讀 41,281評論 3 329
  • 文/蒙蒙 一筐付、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧阻肿,春花似錦瓦戚、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,889評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽畜疾。三九已至,卻和暖如春印衔,著一層夾襖步出監(jiān)牢的瞬間啡捶,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,011評論 1 269
  • 我被黑心中介騙來泰國打工奸焙, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留瞎暑,地道東北人。 一個月前我還...
    沈念sama閱讀 48,119評論 3 370
  • 正文 我出身青樓与帆,卻偏偏與公主長得像了赌,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子鲤桥,可洞房花燭夜當晚...
    茶點故事閱讀 44,901評論 2 355

推薦閱讀更多精彩內(nèi)容