Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 資訊

LayoutInflater 源碼全解析:xml 布局如何變成 View

編輯:Android 資訊

說到 LayoutInflater,大家應該都不陌生,它主要負責加載布局,在 Fragment 的 onCreateView 方法、ListView Adapter 的 getView 方法等諸多場景裡都能看到它的身影。今天我們就來聊聊 LayoutInflater 的用法,以及它加載布局背後的工作原理。

什麼是 LayoutInflater

LayoutInflater 是一個用於把 xml 布局文件加載為 View 或 ViewGroup 對象的工具,我們可以稱之為布局加載器。

用法

獲取 LayoutInflater

首先需要牢記一點:LayoutInflater 本身是一個抽象類,我們無法直接透過 new 的方式拿到它的實例。通常有以下三種獲取途徑:

第一種:

LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

第二種:

LayoutInflater inflater = LayoutInflater.from(context);

第三種:

在Activity內部調用getLayoutInflater()方法

來看看後兩種方法的實現:

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

而在 Activity 內部呼叫 getLayoutInflater 方法,其實調用的是 PhoneWindow 的 mLayoutInflater:

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

可見這幾種方法可謂殊途同歸,本質上都是透過呼叫 Context 的 getSystemService 方法來獲取,最終拿到的都是 PhoneLayoutInflater 這個實現類。至於具體的獲取過程,這裡就不展開分析了。

public class Policy implements IPolicy { ... public LayoutInflater makeNewLayoutInflater(Context context) { return new PhoneLayoutInflater(context); } }

加載布局

下面我們用一個簡單的例子,來演示 LayoutInflater 的用法:

這個例子的目標,是在屏幕上展示一個按鈕;點擊按鈕時,透過 LayoutInflater 把一個橙色背景的 TextView 以 match_parent 的形式加載到一塊寬高為 300dp 的 RelativeLayout 中。

首先創建兩個布局文件:

demo_layout.xml

<?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" android:gravity="center" android:background="#ff750c" android:text="Hello , world !" />

activity_main.xml

<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:text="點擊加載" /> <RelativeLayout android:id="@+id/root" android:layout_width="300dp" android:layout_height="300dp" android:layout_centerInParent="true"/> </RelativeLayout>

MainActivity.java

public class MainActivity extends Activity { RelativeLayout rootView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); rootView = (RelativeLayout) findViewById(R.id.root); findViewById(R.id.button).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { inflateView(); } }); } private void inflateView() { View insideView = LayoutInflater.from(MainActivity.this).inflate(R.layout.demo_layout, null); rootView.addView(insideView); } }

編譯運行,點擊「點擊加載」按鈕,結果如下:

可以看到,我們成功地把 demo_layout.xml 對應布局中的 TextView 加載了進來。

但美中不足的是,加載進來的 TextView 寬高並不是我們期望的 300×300 大小╮(╯▽╰)╭。

於是問題就來了:

  • 為什麼我們在布局文件中給 TextView 設置的寬高屬性失效了呢?
  • LayoutInflater 又是如何把 xml 解析加載成 View 的呢?

而且,inflate 提供了多個不同的重載方法:

  1. inflate(int resource, ViewGroup root)
  2. inflate(int resource, ViewGroup root, boolean attachToRoot)
  3. inflate(XmlPullParser parser, ViewGroup root)
  4. inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot)

上面的例子只用了第一個方法,而且 root 的傳參還是 null。那麼,這些方法有什麼不同?接下來我們就從源碼入手,去尋找這兩個問題的答案。

源碼解析

上文提到,我們獲取到的 LayoutInflater 實例其實是 PhoneLayoutInflater,但 PhoneLayoutInflater 並沒有重寫 inflate 的這幾個方法,所以分析依然要在 LayoutInflater 這個類中展開。

先來比對一下這幾個重載方法:

public View inflate(int resource, ViewGroup root) { // root不為空時,attachToRoot默認為true return inflate(resource, root, root != null); } public View inflate(int resource, ViewGroup root, boolean attachToRoot) { XmlResourceParser parser = getContext().getResources().getLayout(resource); try { return inflate(parser, root, attachToRoot); } finally { parser.close(); } } public View inflate(XmlPullParser parser, ViewGroup root) { // root不為空時,attachToRoot默認為true return inflate(parser, root, root != null); } public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) { ... }

原來,前這幾個方法最終都會彙集到:

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

而且,root 不為空時,attachToRoot 默認為 true。至於布局 id,會透過呼叫 getLayout 方法生成一個 XmlResourceParser 對象。

由於 Android 中的布局文件都是用 xml 編寫的,解析過程自然離不開 xml 解析。常用的 xml 解析方式有 DOM、SAX 和 PULL 三種。DOM 並不適合 xml 文檔較大、內存較小的場景,因此不適用於手機這類內存有限的移動設備。SAX 與 PULL 類似,都具有解析速度快、佔用內存少的優點,而相比之下 PULL 的操作方式更為簡單易用,所以 Android 系統內部在解析各種 xml 時都採用 PULL 解析器。這裡解析布局 xml 文件時,用的正是系統提供的 PULL 方式。

我們接著分析 inflate 方法。

inflate 方法

public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) { synchronized (mConstructorArgs) { final AttributeSet attrs = Xml.asAttributeSet(parser); // 首先注意result初值為root View result = root; try { // 嘗試找到布局文件的根節點 int type; while ((type = parser.next()) != XmlPullParser.START_TAG && type != XmlPullParser.END_DOCUMENT) { // Empty } ... // 獲取當前節點名稱,如merge,RelativeLayout等 final String name = parser.getName(); ... // 處理merge節點 if (TAG_MERGE.equals(name)) { // merge必須依附在一個根View上 if (root == null || !attachToRoot) { throw new InflateException("<merge /> can be used only with a valid " + "ViewGroup root and attachToRoot=true"); } rInflate(parser, root, attrs, false); } else { View temp; // 根據當前信息生成一個View temp = createViewFromTag(root, name, attrs); ... ViewGroup.LayoutParams params = null; if (root != null) { // 如果指定了root參數的話,根據節點的布局參數生成合適的LayoutParams params = root.generateLayoutParams(attrs); // 若指定了attachToRoot為false,會將生成的布局參數應用於上一步生成的View if (!attachToRoot) { temp.setLayoutParams(params); } } // 由上至下,遞歸加載xml內View,並添加到temp裡 rInflate(parser, temp, attrs, true); // 如果root不為空且指定了attachToRoot為true時,會將temp作為子View添加到root中 if (root != null && attachToRoot) { root.addView(temp, params); } // 如果指定的root為空,或者attachToRoot為false的時候,返回的是加載出來的View, // 否則返回root if (root == null || !attachToRoot) { result = temp; } } } ... // 異常處理 return result; } }

這裡要先明確一個概念——布局根 View,注意它與 root 並不是同一回事:

  • root 是我們傳進來的第二個參數;
  • 布局根 View 則是傳入的布局文件根節點所對應的 View。

這個方法主要包含以下幾個步驟:

  1. 首先查找根節點,如果整個 xml 文件解析完畢仍未找到根節點,會拋出異常;
  2. 如果找到的根節點名稱是 merge 標簽,會呼叫 rInflate 方法繼續解析布局,最終返回 root;
  3. 如果是其他標簽(View、TextView 等),會呼叫 createViewFromTag 生成布局根 View,並呼叫 rInflate 遞歸解析剩餘的子 View,添加到布局根 View 中,最後根據 root 和 attachToRoot 參數的情況,返回 view 或 root。

由此我們就能理清 root 與 attachToRoot 參數之間的關係了:

  • root != null, attachToRoot == true:
    傳入的布局會被加載成一個 View,並作為子 View 添加到 root 中,最終返回 root;
    並且這個布局根節點的 android:layout_ 參數會被解析,用來設置 View 的大小。
  • root == null, attachToRoot 無用:
    當 root 為空時,attachToRoot 取什麼值都沒有意義,此時傳入的布局會被加載成一個 View 並直接返回;
    布局根 View 的 android:layout_xxx 屬性會被忽略。
  • root != null, attachToRoot == false:
    傳入的布局會被加載成一個 View 並直接返回;
    布局根 View 的 android:layout_xxx 屬性會被解析成 LayoutParams 並保留(此時 root 只用來參與生成布局根 View 的 LayoutParams)。

現在,我們可以解答文章開頭留下的疑問了。

為何在布局文件中給 TextView 設置的 android:layout 屬性會失效?

回到例子中的代碼,我們加載布局的寫法是:

View insideView = LayoutInflater.from(MainActivity.this).inflate(R.layout.demo_layout, null); rootView.addView(insideView);

也就是 root 傳參為空,正好對應上面第 2 種情況,所以此時布局根 View 的 android:layout_xx 屬性都被忽略了,等於根本沒有給 TextView 設置寬高,自然也就只能按默認的 TextView 大小顯示了。

我們稍微改一下代碼:

LayoutInflater.from(MainActivity.this).inflate(R.layout.demo_layout, rootView);

注意,這段代碼等同於:

LayoutInflater.from(MainActivity.this).inflate(R.layout.demo_layout, rootView, true);

inflate 方法在 root 不為空時,默認會把 attachToRoot 置為 true。

這時就等同於上面的情況 1。由於此時 inflate 會把加載出來的 View 自動添加到 root 中,所以我們要把 rootView.addView(insideView) 這一句移除,否則會遇到這樣的報錯:

java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first. at android.view.ViewGroup.addViewInner(ViewGroup.java:4454) at android.view.ViewGroup.addView(ViewGroup.java:4295) at android.view.ViewGroup.addView(ViewGroup.java:4235) at android.view.ViewGroup.addView(ViewGroup.java:4208)

再跑一遍看看:

終於達到了我們想要的效果!這也印證了上面的第一個結論。

順便借這個例子再拓展驗證一下情況 3,即 root != null, attachToRoot == false 的情形:

View insideView = LayoutInflater.from(MainActivity.this).inflate(R.layout.demo_layout, rootView, false); rootView.addView(insideView);

結果是一樣的(圖就不貼了),也就是說 root != null, attachToRoot == false 時,root 只是用來參與布局根 View 的大小、位置設置。

好了,關於這兩個參數的疑問就先解答到這裡。接下來我們回到代碼,繼續追尋另一個問題的答案,跟進 rInflate 和 createViewFromTag 方法。

rInflate 方法

void rInflate(XmlPullParser parser, View parent, final AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException { ... while (((type = parser.next()) != XmlPullParser.END_TAG || parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) { ... final String name = parser.getName(); // 解析“requestFocus”標簽,讓父View調用requestFocus()獲取焦點 if (TAG_REQUEST_FOCUS.equals(name)) { ... } else if (TAG_INCLUDE.equals(name)) { ... } else if (TAG_MERGE.equals(name)) { ... } else if (TAG_1995.equals(name)) { ... } else { // 調用createViewFromTag生成一個View final View view = createViewFromTag(parent, name, attrs); // 逐層遞歸調用rInflate,解析view嵌套的子View rInflate(parser, view, attrs, true); // 將解析生成子View添加到上一層View中 viewGroup.addView(view, params); } } // 內層子View被解析出來後,將調用其父View的“onFinishInflate()”回調 if (finishInflate) parent.onFinishInflate(); }

首先是對幾個特殊標簽的處理,比如 requestFocus、include 等,為了抓住主線,我們不展開討論,直接看最後那個 else 分支。原來,rInflate 主要做了兩件事:呼叫 createViewFromTag 生成當前解析到的 View 節點,並遞歸呼叫 rInflate 逐層生成子 View,再把它們添加到各自的上一層 View 節點中。而當某個節點下所有子節點 View 都解析生成完畢後,才會觸發 onFinishInflate 回調。所以說,createViewFromTag 才是真正生成 View 的地方。

createViewFromTag 方法

View createViewFromTag(View parent, String name, AttributeSet attrs) { ... try { View view; if (mFactory2 != null) view = mFactory2.onCreateView(parent, name, mContext, attrs); else if (mFactory != null) view = mFactory.onCreateView(name, mContext, attrs); else view = null; if (view == null && mPrivateFactory != null) { view = mPrivateFactory.onCreateView(parent, name, mContext, attrs); } // 三個Factory都不存在調用LayoutInflater自己的onCreateView或者createView // // 如果View標簽中沒有".",則代表是系統的widget,則調用onCreateView, // 這個方法會通過"createView"方法創建View // 不過前綴字段會自動補"android.view."前綴。 if (view == null) { if (-1 == name.indexOf('.')) { view = onCreateView(parent, name, attrs); } else { view = createView(name, null, attrs); } } return view; } catch (InflateException e) { ... } ... } public interface Factory { public View onCreateView(String name, Context context, AttributeSet attrs); }

它會依次嘗試呼叫 mFactory2、mFactory 和 mPrivateFactory 三者之一的 onCreateView 方法來創建 View。如果這幾個 Factory 都為 null,就改由 LayoutInflater 自己的 onCreateView 或 createView 來實例化 View。

自定義 Factory 一個十分實用的場景,就是用來實現應用換膚,感興趣的讀者可以參考我開源的 Android-Skin-Loader 中的具體細節。

通常情況下,自定義工廠 mFactory2、mFactory 和私有工廠 mPrivateFactory 都是空的;只有當 Activity 繼承自 AppCompatActivity 時,才會存在自定義 Factory。所以,生成 View 的重任最終就落在了 onCreateView 和 createView 身上。

onCreateView 調用的其實就是 createView,即當 View 的節點名稱中沒有 . 時,會自動補上 android.view. 前綴(也就是完整類名):

protected View onCreateView(String name, AttributeSet attrs) throws ClassNotFoundException { return createView(name, "android.view.", attrs); }

接著我們繼續關注 createView 的實現。

createView 方法

public final View createView(String name, String prefix, AttributeSet attrs) throws ClassNotFoundException, InflateException { Constructor<? extends View> constructor = sConstructorMap.get(name); Class<? extends View> clazz = null; try { if (constructor == null) { // 緩存中不存在某View的構造方法,先new出來放緩存中 clazz = mContext.getClassLoader().loadClass( prefix != null ? (prefix + name) : name).asSubclass(View.class); ... constructor = clazz.getConstructor(mConstructorSignature); sConstructorMap.put(name, constructor); } else { ... } Object[] args = mConstructorArgs; args[1] = attrs; return constructor.newInstance(args); } catch (NoSuchMethodException e) { ... } }

這是最後一步,非常容易理解:透過傳入的全類名,呼叫 newInstance 創建該類的實例並返回,返回的這個實例就是我們需要的 View。結合前面遞歸解析的過程,每一個層級的節點都會被生成一個個的 View,並根據 View 的層級關係被 add 到對應的直接父 View(上層節點)中,最終返回一個包含了所有解析好的子 View 的布局根 View。至此,透過 xml 加載 View 的整個原理就分析完成了。

總結

最後,我們再回顧一下上面的分析結論。

inflate 方法的參數關係

  • root != null, attachToRoot == true
    傳入的布局會被加載成一個 View 並作為子 View 添加到 root 中,最終返回 root;
    並且這個布局根節點的 android:layout_xxx 參數會被解析,用來設置 View 的大小;
  • root == null, attachToRoot 無意義
    當 root 為空時,attachToRoot 無論取什麼值都沒有意義。此時傳入的布局會被加載成一個 View 並直接返回;
    布局根 View 的 android:layout_xxx 屬性會被忽略,也就是說 android:layout_xx 屬性只有依附在某個 ViewGroup 中才能生效;
  • root != null, attachToRoot == false
    傳入的布局會被加載成一個 View 並直接返回;
    布局根 View 的 android:layout_xxx 屬性會被解析成 LayoutParams 並設置在 View 上,此時 root 只用於設置布局根 View 的大小和位置。

加載 xml 布局的原理

說到底,就是從根節點開始,遞歸解析 xml 的每一個節點。每一步遞歸的過程是:透過節點名稱(全類名),使用 ClassLoader 創建對應類的實例,也就是 View,然後把這個 View 添加到它的上層節點(父 View)中,同時解析對應 xml 節點的屬性作為 View 的屬性。每個層級的節點都會被生成一個個的 View,並根據 View 的層級關係 add 到對應的直接父 View(上層節點)中,最終返回一個包含了所有解析好的子 View 的布局根 View。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved