編輯:關於 Android 程式設計
談到自定義 View,就繞不開 LayoutInflater。代碼裡當然可以直接 new 出各種 View,再一個個 setLayoutParams 去擺位置,但這種做法在簡單布局上還勉強能用,一旦結構複雜起來就變得非常笨拙,性能與可維護性上的細節優化更是難以兼顧。這時候,LayoutInflater 就是那個必須掌握的工具。
它的職責很單一:把 res/layout 目錄下的 XML 布局文件,實例化成對應的 View 對象樹。好處不言自明——XML 可以可視化編寫、可預覽、可替換。
方式一,在 Activity 中直接調用:
LayoutInflater inflater = getLayoutInflater();
方式二,通過 Context 拿單例:
LayoutInflater inflater = LayoutInflater.from(mContext);
方式三,向系統服務索取:
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);翻一下源碼就會發現,前兩種方式最終都彙聚到第三種。拿到實例之後,調用它的 inflate 方法即可把 XML 變成 View。
假設 MainActivity 對應的布局是 activity_main.xml,裡面只有一個空的 RelativeLayout 作為容器:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@+id/root_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
</RelativeLayout>再新建一個 layout_textview.xml,內容是一個簡單的 TextView:
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@color/colorAccent"
android:gravity="center"
android:padding="10dp"
android:text="Hello World!!!"
android:textColor="@color/white"
android:textSize="18sp" />接著在 Activity 中把這個 TextView 加載並添加到容器裡:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
RelativeLayout mainLayout = (RelativeLayout) findViewById(R.id.root_layout);
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
TextView textView = (TextView) inflater.inflate(R.layout.layout_textview, null);
mainLayout.addView(textView);
}這裡用的是 inflate(int resource, ViewGroup root) 這個重載,跟進源碼可以看到它其實轉調了另一個版本:
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
return inflate(resource, 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 實際上有三個參數:
resource:int 型,要被實例化的布局文件資源 id;
root:ViewGroup 型,根布局或父布局,不為空時它將作為新 View 的 LayoutParams 依據;
attachToRoot:boolean 型,是否在加載完成後直接把新 View 掛到 root 上。
運行效果:

現在把 TextView 的尺寸改一改,寬度撐滿父容器、高度固定 150dp:
<?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="150dp"
android:background="@color/colorAccent"
android:gravity="center"
android:padding="10dp"
android:text="Hello World!!!"
android:textColor="@color/white"
android:textSize="18sp" />再運行一次,畫面卻毫無變化:

問題出在哪?回到 inflate 的三個參數——我們把 root 傳成了 null。改成傳入真實的父容器,並把 attachToRoot 設為 false:
inflater.inflate(R.layout.layout_textview, mainLayout, false);
這一次符合預期了:

結論很清楚:XML 布局文件最外層節點的 layout_width / layout_height 必須有 root 才能生效。這也說明了另一件事——layout_width 和 layout_height 本質上是「相對於父布局」的屬性,XML 裡並沒有真正設置 View 自身的 height 與 width。
至於第三個參數 attachToRoot,它決定實例化之後是否順手把 View 添加進 root。傳 true 就省了我們手動調 addView() 的步驟。
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 {
parser.close();
}
}
public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
final Context inflaterContext = mContext;
final AttributeSet attrs = Xml.asAttributeSet(parser);
View result = root;
final String name = parser.getName();
if (TAG_MERGE.equals(name)) {
// merge 標籤必須配合有效的 root 且 attachToRoot 為 true
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 {
// 先根據標籤名創建 XML 中的根 View
final View temp = createViewFromTag(root, name, inflaterContext, attrs);
ViewGroup.LayoutParams params = null;
if (root != null) {
// 關鍵:根據 root 的類型生成對應的 LayoutParams
params = root.generateLayoutParams(attrs);
if (!attachToRoot) {
temp.setLayoutParams(params);
}
}
// 遞歸創建子 View
rInflateChildren(parser, temp, attrs, true);
if (root != null && attachToRoot) {
root.addView(temp, params);
}
if (root == null || !attachToRoot) {
result = temp;
}
return result;
}
}源碼把前面的推測坐實了:inflate 會依據傳入的 root 生成相應類型的 LayoutParams,再賦值給新創建的 View。root 是 RelativeLayout,生成的就是 RelativeLayout.LayoutParams。
我們可以再驗證一次——給 TextView 加上只在 RelativeLayout 下才有意義的 layout_alignParentBottom:
<?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="150dp"
android:layout_alignParentBottom="true"
android:background="@color/colorAccent"
android:gravity="center"
android:padding="10dp"
android:text="Hello World!!!"
android:textColor="@color/white"
android:textSize="18sp" />效果確實生效了:

順帶一提,我們平時在 Activity 裡調用的 setContentView(),最終也是走進 LayoutInflater 的 inflate 方法。
inflate 的三個參數:
resource:int 型,傳入將被實例化的布局文件;
root:ViewGroup 型,根布局或父布局,不為空時會為生成的 View 套上 root 對應類型的 LayoutParams;
attachToRoot:boolean 型,是否在加載後直接把 View 依附到 root 上。
Android 異步消息處理機制詳解:從示例到 Handler 源碼剖析
最近事情不多,養病期間索性把之前零散積累的知識點整理成文,既方便自己複習,也希望能幫到別人。 一、為什麼要談這個話題 選這個題目有三個原因:一是在 GitHub 上看到有
線上搜索 Android 源代碼的實用方法
在 Google 缺席的年代,程序員遇到問題唯一的出路就是讀源碼。如今搜尋引擎能解決大部分開發問題,但若想真正理解某個 API 的內部運行機制,最終還是得回到源碼本身。
自訂 View 實作隨機驗證碼:CheckView 與工具類拆分
對不少 Android 入門者來說,「自訂 View」四個字聽起來就有點可怕,但它其實是通往進階的必經之路。與其死讀理論,不如挑一個具體題目反覆練習。本文就以「隨機驗證碼
Android 自定義圖片選擇元件:相冊、拍照、裁剪與刪除動畫
元件目標 本文實作一個類似社群貼文選圖的自定義元件,支援從相冊選擇圖片、拍照取得圖片、長按顯示刪除按鈕、動畫提示,以及達到數量上限後隱藏新增按鈕。 加號圖片永遠在最