天天看點

LayoutInflater源碼簡析

關于LayoutInflater的基本用法就不再累述了,本篇主要通過分析inflate()的源碼搞清幾個參數的作用。

首先來看一個Demo,這個Demo很簡單就是通過調用LayoutInflater的inflate方法擷取一個藍色背景的TextView并以match_parent的形式添加到一個300dp*100dp的RelativeLayout上,我們傳遞不同的參數來看一下實作效果之間的差别。

先來看一下這兩個布局檔案

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:background="@android:color/holo_blue_dark"
          android:gravity="center"
          android:text="Hello World"
          android:textColor="#fff"
          android:textSize="18sp">

</TextView>
           
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <RelativeLayout
        android:id="@+id/content"
        android:layout_width="300dp"
        android:layout_height="100dp"
        android:layout_gravity="center_horizontal"
        android:orientation="vertical">

    </RelativeLayout>

    <TextView
        android:id="@+id/params"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="12dp"
        android:paddingRight="12dp"
        android:textColor="#555"
        android:textSize="14sp"/>

</LinearLayout>
           

再來看一下實作代碼和對應的實作效果,同時我們輸出TextView的寬和高。

No.1

View textView = LayoutInflater.from(this).inflate(R.layout.textview, null);
content.addView(textView);
           
LayoutInflater源碼簡析

No.2

LayoutInflater源碼簡析

No.3

View textView = LayoutInflater.from(this).inflate(R.layout.textview, content, false);
content.addView(textView);
           
LayoutInflater源碼簡析

可以看到隻有第二和第三種方式實作了我們想要的效果,為什麼第一種不可以呢?根據輸出的TextView的寬和高我們應該能猜出一些端倪。那就是通過第二,第三種方式得到的TextView設定了寬高都為match_parent的LayoutParams,為什麼會這樣呢,讓我們通過源碼一探究竟。

注:

/**
         * Special value for the height or width requested by a View.
         * MATCH_PARENT means that the view wants to be as big as its parent,
         * minus the parent's padding, if any. Introduced in API Level 8.
         */
        public static final int MATCH_PARENT = -;

        /**
         * Special value for the height or width requested by a View.
         * WRAP_CONTENT means that the view wants to be just large enough to fit
         * its own internal content, taking its own padding into account.
         */
        public static final int WRAP_CONTENT = -;
           

源碼簡析

首先對比一下幾個重載方法,可以看到除了上面我們用到的兩種還有兩種。

public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
        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();
        }
}

public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
    ...
}
           

不過前三個最終調用的都是:

public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
    ...
}
           

而且我們還可以發現,root != null時,attachToRoot預設為true,布局id會被通過調用getLayout方法生成一個XmlResourceParser對象。我們繼續分析inflate方法

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[];
            mConstructorArgs[] = inflaterContext;
            // 首先注意result的初始值為root,也就是我們傳進來的
            View result = root;

            try {
                // 嘗試找到根節點
                int type;
                while ((type = parser.next()) != XmlPullParser.START_TAG &&
                        type != XmlPullParser.END_DOCUMENT) {
                }

                // 擷取目前節點名稱
                final String name = parser.getName();

                // 處理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");
                    }
                    rInflate(parser, root, inflaterContext, attrs, false);
                } else {
                    // 根據擷取到的節點名建立根View
                    final View temp = createViewFromTag(root, name, inflaterContext, attrs);

                    ViewGroup.LayoutParams params = null;

                    // 如果我們傳遞進來一個ViewGroup,那麼就會根據我們傳遞進來的ViewGroup
                    // 生成LayouParams
                    if (root != null) {
                        params = root.generateLayoutParams(attrs);
                        // 如果attachToRoot為false,那麼将LayoutParams添加到根View
                        // 否則會走下面的代碼,直接将根View添加到我們傳遞進來的ViewGroup上
                        if (!attachToRoot) {
                            temp.setLayoutParams(params);
                        }
                    }

                    // 擷取根節點下面所有的子View
                    rInflateChildren(parser, temp, attrs, true);

                    // 如果我們傳遞進來一個ViewGroup并且attachToRoot為ture
                    // 則将擷取到的view添加到我們傳遞進來的ViewGroup上,同時布局
                    if (root != null && attachToRoot) {
                        root.addView(temp, params);
                    }

                    // 如果我們沒有傳遞進來ViewGroup或者attachToRoot為false,則将生成的
                    // 根View傳回,否則傳回root,也就是我們傳遞進來的ViewGroup
                    if (root == null || !attachToRoot) {
                        result = temp;
                    }
                }
            } catch (XmlPullParserException e) {

            } catch (Exception e) {

            } finally {

            }
            return result;
        }
    }
           
根據以上分析我們發現這個方法主要有下面幾個步驟:
  1. 首先查找根節點,如果整個xml檔案解析完畢也沒看到根節點,會抛出異常;
  2. 如果查找到的根節點名稱是merge标簽,會調用rInflate方法繼續解析布局,最終傳回root;
  3. 如果是其他标簽(View、TextView等),會調用createViewFromTag生成布局根View,并調用rInflate遞歸解析餘下的子View,添加至布局根View中,最後視root和attachToRoot參數的情況最終傳回view或者root。
從這裡我們可以理清root和attachToRoot參數的關系了:
  • root == null, attachToRoot無用:

    當root為空時,attachToRoot是什麼都沒有意義,此時傳進來的布局會被加載成為一個View并直接傳回;

    布局根View的android:layout_xxx屬性會被忽略。

  • root != null, attachToRoot == true:

    傳進來的布局會被加載成為一個View并作為子View添加到root中,最終傳回root;

    而且這個布局根節點的android:layout_xxx參數會被解析用來設定View的大小。

  • root != null, attachToRoot == false:

    傳進來的布局會被加載成為一個View并直接傳回。

    布局根View的android:layout_xxx屬性會被解析成LayoutParams并保留。(root隻用來參與生成布局根View的LayoutParams)

想必到這不用我說大家也很清楚為什麼Demo中通過第一種方式加載布局無法實作我們想要的效果了。

總結

可能以前我們怎麼也不明白這些參數的作用,可是今天通過簡單的分析源碼我們就可以發現其中的端倪,而且要比看别人的介紹印象更加深刻,是以以後遇到不懂不明白的,Read the fucking source code,沒有比這更直接有效的了。

其實通過上面簡析inflate方法源碼的過程,我們對加載xml布局的原理也有了一些簡單的了解。其實就是從根節點開始,遞歸解析xml的每個節點,根據到的節點名通過反射生成一個個View,同時解析該節點的屬性作為View的屬性,然後根據View的層級關系add到對應的父View(上層節點)中,最終傳回一個包含了所有解析好的子View的布局根View。那麼具體是不是這樣的,且看下回分解。

繼續閱讀