LayoutInflater.inflate源碼詳解

LayoutInflater.inflate源碼詳解
LayoutInflater的inflate方法相信大家都不陌生,在Fragment的onCreateView中或者在BaseAdapter的getView方法中我們都會經常用這個方法來實例化出我們需要的View.
假設我們有一個需要實例化的佈局文件menu_item.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/id_menu_title_tv"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:gravity="center_vertical"
        android:textColor="@android:color/black"
        android:textSize="16sp"
        android:text="@string/menu_item"/>
</LinearLayout>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
我們想在BaseAdapter的getView()方法中對其進行實例化,其實例化的方法有三種,分別是:

2個參數的方法:
convertView = mInflater.inflate(R.layout.menu_item, null);
1
3個參數的方法(attachToRoot=false):
convertView = mInflater.inflate(R.layout.menu_item, parent, false);
1
3個參數的方法(attachToRoot=true):
convertView = mInflater.inflate(R.layout.menu_item, parent, true);
1
究竟我們應該用哪個方法進行實例化View,這3個方法又有什麼區別呢?如果有同學對三個方法的區別還不是特別清楚,那麼就和我一起從源碼的角度來分析一下這個問題吧.

源碼
inflate
我們先來看一下兩個參數的inflate方法,源碼如下:

public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
    return inflate(resource, root, root != null);
}
1
2
3
從代碼我們看出,其實兩個參數的inflate方法根據父佈局parent是否爲null作爲第三個參數來調用三個參數的inflate方法,三個參數的inflate方法源碼如下:

public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
    // 獲取當前應用的資源集合
    final Resources res = getContext().getResources();
    // 獲取指定資源的xml解析器
    final XmlResourceParser parser = res.getLayout(resource);
    try {
        return inflate(parser, root, attachToRoot);
    } finally {
        // 返回View之前關閉parser資源
        parser.close();
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
這裏需要解釋一下,我們傳入的資源佈局id是無法直接實例化的,需要藉助XmlResourceParser.
而XmlResourceParser是藉助Android的pull解析方法是解析佈局文件的.繼續跟蹤inflate方法源碼:

public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
    synchronized (mConstructorArgs) {
        // 獲取上下文對象,即LayoutInflater.from傳入的Context.
        final Context inflaterContext = mContext;
        // 根據parser構建XmlPullAttributes.
        final AttributeSet attrs = Xml.asAttributeSet(parser);
        // 保存之前的Context對象.
        Context lastContext = (Context) mConstructorArgs[0];
        // 賦值爲傳入的Context對象.
        mConstructorArgs[0] = inflaterContext;
        // 注意,默認返回的是父佈局root.
        View result = root;

        try {
            // 查找xml的開始標籤.
            int type;
            while ((type = parser.next()) != XmlPullParser.START_TAG &&
                    type != XmlPullParser.END_DOCUMENT) {
                // Empty
            }

            // 如果沒有找到有效的開始標籤,則拋出InflateException異常.
            if (type != XmlPullParser.START_TAG) {
                throw new InflateException(parser.getPositionDescription()
                        + ": No start tag found!");
            }

            // 獲取控件名稱.
            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;

                // 如果傳入的parent不爲空.
                if (root != null) {
                    if (DEBUG) {
                        System.out.println("Creating params from root: " +
                                root);
                    }
                    // 創建父類型的LayoutParams參數.
                    params = root.generateLayoutParams(attrs);
                    if (!attachToRoot) {
                        // 如果實例化的View不需要添加到父佈局上,則直接將根據父佈局生成的params參數設置
                        // 給它即可.
                        temp.setLayoutParams(params);
                    }
                }

                // 遞歸的創建當前佈局的所有控件
                rInflateChildren(parser, temp, attrs, true);

                // 如果傳入的父佈局不爲null,且attachToRoot爲true,則將實例化的View加入到父佈局root中
                if (root != null && attachToRoot) {
                    root.addView(temp, params);
                }

                // 如果父佈局爲null或者attachToRoot爲false,則將返回值設置成我們實例化的View
                if (root == null || !attachToRoot) {
                    result = temp;
                }
            }

        } catch (XmlPullParserException e) {
            InflateException ex = new InflateException(e.getMessage());
            ex.initCause(e);
            throw ex;
        } catch (Exception e) {
            InflateException ex = new InflateException(
                    parser.getPositionDescription()
                            + ": " + e.getMessage());
            ex.initCause(e);
            throw ex;
        } finally {
            // Don't retain static reference on context.
            mConstructorArgs[0] = lastContext;
            mConstructorArgs[1] = null;
        }

        Trace.traceEnd(Trace.TRACE_TAG_VIEW);

        return result;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
上述代碼中的關鍵部分我已經加入了中文註釋.從上述代碼中我們還可以發現,我們傳入的佈局文件是通過createViewFromTag來實例化每一個子節點的.

createViewFromTag
函數源碼如下:

/**
 * 方便調用5個參數的方法,ignoreThemeAttr的值爲false.
 */
private View createViewFromTag(View parent, String name, Context context, AttributeSet attrs) {
    return createViewFromTag(parent, name, context, attrs, false);
}

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

    // 特殊處理“1995”這個標籤(ps: 平時我們寫xml佈局文件時基本沒有使用過).
    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 (InflateException e) {
        throw e;

    } catch (ClassNotFoundException e) {
        final InflateException ie = new InflateException(attrs.getPositionDescription()
                + ": Error inflating class " + name);
        ie.initCause(e);
        throw ie;

    } catch (Exception e) {
        final InflateException ie = new InflateException(attrs.getPositionDescription()
                + ": Error inflating class " + name);
        ie.initCause(e);
        throw ie;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
在createViewFromTag方法中,最終是通過createView方法利用反射來實例化view控件的.

createView
public final View createView(String name, String prefix, AttributeSet attrs)
    throws ClassNotFoundException, InflateException {
    // 以View的name爲key, 查詢構造函數的緩存map中是否已經存在該View的構造函數.
    Constructor<? extends View> constructor = sConstructorMap.get(name);
    Class<? extends View> clazz = null;

    try {
        // 構造函數在緩存中未命中
        if (constructor == null) {
            // 通過類名去加載控件的字節碼
            clazz = mContext.getClassLoader().loadClass(prefix != null ? (prefix + name) : name).asSubClass(View.class);
            // 如果有自定義的過濾器並且加載到字節碼,則通過過濾器判斷是否允許加載該View
            if (mFilter != null && clazz != null) {
                boolean allowed = mFilter.onLoadClass(clazz);
                if (!allowed) {
                    failNotAllowed(name, prefix, attrs);
                }
            }
            // 得到構造函數
            constructor = clazz.getConstructor(mConstructorSignature);
            constructor.setAccessible(true);
            // 緩存構造函數
            sConstructorMap.put(name, constructor);
        } else {
            if (mFilter != null) {
                // 過濾的map是否包含了此類名
                Boolean allowedState = mFilterMap.get(name);
                if (allowedState == null) {
                    // 重新加載類的字節碼
                    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);
                }
            }
        }

        // 實例化類的參數數組(mConstructorArgs[0]爲Context, [1]爲View的屬性)
        Object[] args = mConstructorArgs;
        args[1] = attrs;
        // 通過構造函數實例化View
        final View view = constructor.newInstance(args);
        if (View instanceof ViewStub) {
            final ViewStub viewStub = (ViewStub) view;
            viewStub.setLayoutInflater(cloneInContext((Context)args[0]))
        }
        return view;
    } catch (NoSunchMethodException e) {
        // ......
    } catch (ClassNotFoundException e) {
        // ......
    } catch (Exception e) {
        // ......
    } finally {
        // ......
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
總結
通過學習了inflate函數源碼,我們再回過頭去看BaseAdapter的那三種方法,我們可以得出的結論是:

第一種方法使用不夠規範, 且會導致實例化View的LayoutParams屬性失效.(ps: 即layout_width和layout_height等參數失效, 因爲源碼中這種情況的LayoutParams爲null).
第二種是最正確,也是最標準的寫法.
第三種由於attachToRoot爲true,所以返回的View其實是父佈局ListView,這顯然不是我們想要實例化的View.因此,第三種寫法是錯誤的.
————————————————
版權聲明:本文爲CSDN博主「低調小一」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/wzy_1988/article/details/52095398

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章