編輯:Android 技術基礎
談到 Android 的介面,多數人腦中浮現的流程是:寫好一份 XML 版面配置,然後在 Activity 裡呼叫 setContentView() 把它掛上去。但你可能不知道,這一步的底層其實正是本節的主角——LayoutInflater(版面配置服務)。它負責把 XML 標籤逐一解析、實例化成真正的 View 物件,用的正是 Android 內建的 Pull 解析器。
如果你曾經有過「想在執行期才決定要放哪些元件」的需求,那 LayoutInflater 就是必備工具。本節就從觀念到實作,把它的常見用法完整走一遍。
參考資料:LayoutInflater 官方 API 文件
它是一個系統服務,作用是把與 XML 版面配置檔對應的 View 物件真的 new 出來。由於它與 Context 綁定,因此不能直接 new,必須透過 getLayoutInflater() 或 getSystemService() 取得當前 Context 對應的實例。
LayoutInflater inflater1 = LayoutInflater.from(this); LayoutInflater inflater2 = getLayoutInflater(); LayoutInflater inflater3 = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
三種寫法效果相同,其中後兩者底層走的其實就是第一種。挑順手的用即可,團隊專案建議統一風格。
public View inflate(int resource, ViewGroup root, boolean attachToRoot)
三個參數的意義如下:
① resource:要載入的版面配置資源 ID,例如 R.layout.activity_main。
② root:可選的父容器。若不需要外層容器,直接傳 null。
③ attachToRoot:是否把載入的版面掛到 root 上。若不顯式指定,root 不為 null 時預設為 true;root 為 null 時這個參數就沒有意義了。
簡單記:attachToRoot 決定「要不要幫這份版面套上一層外容器並直接掛上去」。為 true 時,inflate 回傳的是 root;為 false 時,回傳的是版面本身的根節點,同時 LayoutParams 會被套用到該根節點上——這也是為什麼「只想取回 View 稍後自己 addView」時,通常傳 null + false。
取得 View 之後,可以用 LayoutInflater.LayoutParams(或其子類,如 RelativeLayout.LayoutParams)來描述位置與尺寸。以 RelativeLayout 為例,還能透過 addRule() 指定對齊規則:對齊父容器、對齊兄弟元件、設定 margin 等等,全由你的版面設計決定。
我們早就習慣用 XML 拉版面,但某些情境下確實需要透過程式碼動態塞入元件。不過實務上不建議用純 Java 完成整個頁面:程式碼量會迅速膨脹,可讀性變差,也不利於把畫面與邏輯分離。
比較健康的做法是:XML 負責骨架,Java 負責動態增刪與微調。
Step 1:建立容器與元件
LinearLayout ly = new LinearLayout(this); Button btnOne = new Button(this);
Step 2:設定屬性
XML 上的屬性,在 Java 這邊大多只是在前面加上 set。例如:
ly.setOrientation(LinearLayout.VERTICAL);
btnOne.setText("按鈕1");
btnOne.setPadding(0, 0, 0, 0);
Step 3:用 LayoutParams 描述尺寸與位置,再放進容器
可以把 LayoutParams 想成「加入父容器時附帶的一張資料卡」,裡頭寫著尺寸與定位資訊。
LinearLayout.LayoutParams lp1 = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
若父容器是 RelativeLayout,定位就靠 addRule(),而且可以連續呼叫多次:
RelativeLayout rly = new RelativeLayout(this);
RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp2.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
Button btnOne = new Button(this);
rly.addView(btnOne, lp2);
Step 4:交給 setContentView() 顯示
另外,若要移除已加入的 View,呼叫父容器的 removeView(view) 即可。
RelativeLayout 有一個實務上的小地雷:當 A 要參照 B 定位時,B 必須手動指定 id。以下範例讓「按鈕1」水平垂直居中,「按鈕2」貼在其下方並對齊父容器右側。
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
RelativeLayout rly = new RelativeLayout(this);
Button btnOne = new Button(this);
btnOne.setText("按鈕1");
Button btnTwo = new Button(this);
btnTwo.setText("按鈕2");
// 被參照的元件必須手動指定 id
btnOne.setId(123);
RelativeLayout.LayoutParams rlp1 = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
rlp1.addRule(RelativeLayout.CENTER_IN_PARENT);
RelativeLayout.LayoutParams rlp2 = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
rlp2.addRule(RelativeLayout.BELOW, 123);
rlp2.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
rly.addView(btnTwo, rlp2);
rly.addView(btnOne, rlp1);
setContentView(rly);
}
}

純 Java 拉版面的場合其實不多,日常更常見的是「XML 打底 + 執行期動態補上元件或整段版面」。以下兩個範例示範這兩種典型寫法。
先準備版面配置 activity_main.xml:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/txtTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="我是由 XML 載入的版面" />
</RelativeLayout>
寫法 A:先 inflate 取得容器,addView 之後再 setContentView
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button btnOne = new Button(this);
btnOne.setText("我是動態加入的按鈕");
RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp2.addRule(RelativeLayout.CENTER_IN_PARENT);
LayoutInflater inflater = LayoutInflater.from(this);
RelativeLayout rly = (RelativeLayout) inflater
.inflate(R.layout.activity_main, null)
.findViewById(R.id.RelativeLayout1);
rly.addView(btnOne, lp2);
setContentView(rly);
}
}
寫法 B:先 setContentView,再用 findViewById 取得容器
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnOne = new Button(this);
btnOne.setText("我是動態加入的按鈕");
RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp2.addRule(RelativeLayout.CENTER_IN_PARENT);
RelativeLayout rly = (RelativeLayout) findViewById(R.id.RelativeLayout1);
rly.addView(btnOne, lp2);
}
}
重點整理:兩種寫法的差別只在「容器從哪裡來」。A 版用 inflate 自己解析並取出根節點;B 版因為 setContentView 已經把整份 XML 綁定到視圖樹上,直接 findViewById 就能拿到。切記:setContentView 掛上去的是 XML 的根節點。
主版面 activity_main.xml,只放一顆觸發用的按鈕:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="@+id/btnLoad"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="動態載入版面" />
</RelativeLayout>
待載入的 inflate.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@+id/ly_inflate"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="我是由 Java 動態載入的版面" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="我是版面裡的小按鈕" />
</LinearLayout>
MainActivity.java:點擊按鈕後才把 inflate.xml 塞進主版面。
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final LayoutInflater inflater = LayoutInflater.from(this);
final RelativeLayout rly = (RelativeLayout) findViewById(R.id.RelativeLayout1);
Button btnLoad = (Button) findViewById(R.id.btnLoad);
btnLoad.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 載入待加入的版面,並取得最外層根節點
LinearLayout ly = (LinearLayout) inflater
.inflate(R.layout.inflate, null, false)
.findViewById(R.id.ly_inflate);
// 描述它在父容器中的尺寸與位置
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.CENTER_IN_PARENT);
rly.addView(ly, lp);
}
});
}
}

流程拆解:
① 取得外層容器:
findViewById(R.id.RelativeLayout1)② 取得 inflater 並載入目标版面,再 findViewById 取出它的根節點
③ 用 RelativeLayout.LayoutParams 描述尺寸與對齊規則
④
rly.addView(ly, lp)掛上去,完成
最後附上 inflate() 的實作。看完你會發現它並不神秘——本質上就是一次 Pull 解析,再遞迴把標籤變成 View。
public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {
synchronized (mConstructorArgs) {
final AttributeSet attrs = Xml.asAttributeSet(parser);
mConstructorArgs[0] = mContext;
View result = root;
try {
int type;
while ((type = parser.next()) != XmlPullParser.START_TAG && type != XmlPullParser.END_DOCUMENT) {
}
if (type != XmlPullParser.START_TAG) {
throw new InflateException(parser.getPositionDescription() + ": No start tag found!");
}
final String name = parser.getName();
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, attrs);
} else {
View temp = createViewFromTag(name, attrs);
ViewGroup.LayoutParams params = null;
if (root != null) {
params = root.generateLayoutParams(attrs);
if (!attachToRoot) {
temp.setLayoutParams(params);
}
}
rInflate(parser, temp, attrs);
if (root != null && attachToRoot) {
root.addView(temp, params);
}
if (root == null || !attachToRoot) {
result = temp;
}
}
} catch (XmlPullParserException e) {
InflateException ex = new InflateException(e.getMessage());
ex.initCause(e);
throw ex;
} catch (IOException e) {
InflateException ex = new InflateException(
parser.getPositionDescription() + ": " + e.getMessage());
ex.initCause(e);
throw ex;
}
return result;
}
}
從原始碼也能看出 <merge> 的限制:它必須搭配非 null 的 root 且 attachToRoot 為 true,否則直接丟 InflateException。這解釋了為什麼 merge 標籤總是寫在「要被插入到某個父容器」的版面裡。
LayoutInflater 是動態介面的地基:inflate 的三個參數、attachToRoot 的回傳差異、LayoutParams 的定位方式,以及「動態加 View」與「動態載入整份 XML」這兩種常見套路,都是日常開發會反覆用到的知識。把這些吃透,之後處理 RecyclerView 的 ItemView、Dialog 的自訂內容、Fragment 的 view 建立,都會輕鬆許多。
Android 開發環境搭建:JDK、IDE 選擇與 ADB 基礎
主流開發環境常見的 Android 開發環境包含 Eclipse ADT、Android Studio 與 IntelliJ IDEA。目前官方主要推薦 Android
ZoomControls 教學:用兩個按鈕縮放圖片
看圖程式的縮放按鈕該怎麼做?ZoomControls 把「放大」與「縮小」兩個圓形按鈕打包成一個元件,你只要接上自己的縮放邏輯就能用。它的運作原理不複雜:以 Matrix
Intent 進階:Activity 之間的雙向資料傳遞
Android 中 Activity 之間的跳轉靠 Intent 完成。本文用一個小例子把「去」與「回」兩段路都走通:MainActivity 用 startActivi
Paint Shader 圖像渲染:五種 Shader 解析
Shader 的作用Shader 可讓 Paint 以圖形或漸層方式填色,而不只是單一顏色。Android 中常見的 Shader 包含 BitmapShader、Lin