在 Android 3.0 (API Level 11) 推出後,Fragment 成為開發者構建適應不同螢幕尺寸與解析度應用的核心組件。本文將系統性介紹 Fragment 的核心概念、生命週期、建立方式、與 Activity 的互動機制,並提供實戰程式碼範例,協助您快速掌握這項關鍵技術。
傳統上,Activity 是 UI 的基本單元。然而,隨著平板電腦、大螢幕手機、折疊裝置的普及,單一 Activity 難以同時滿足「手機上單欄顯示」與「平板上雙欄並排」的設計需求。Fragment 解決了這個痛點:它是一個模組化的 UI 片段,擁有獨立的生命週期與輸入事件處理,可動態組合進 Activity 中。

以新聞應用為例:在平板上,左側 Fragment 顯示文章列表,右側 Fragment 顯示文章內容,兩者並存于同一 Activity;在手機上,因空間有限,僅顯示列表 Fragment,點選文章後啟動新 Activity 載入內容 Fragment。這種「一碼多端」的彈性,正是 Fragment 的核心價值。
Fragment 必須繼承 android.app.Fragment (或支援庫中的 androidx.fragment.app.Fragment)。其程式碼結構與 Activity 相似,包含 onCreate()、onCreateView()、onPause() 等回呼方法。遷移既有專案時,只需將 Activity 回呼中的邏輯移至對應的 Fragment 回呼即可。
onListItemClick() 等便利方法,類似 ListActivity。
開發時最常覆寫的三個核心方法:
public class MainFragment extends Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 初始化需保留的組件(如資料模型、執行緒等)
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// 載入佈局 XML 並回傳根 View
return inflater.inflate(R.layout.fragment_main, container, false);
}
@Override
public void onPause() {
super.onPause();
// 儲存持久化資料(使用者可能不會返回)
}
}
透過 LayoutInflater 將 XML 佈局轉為 View 階層:
public static class ExampleFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// false 表示不立即附加到 container,由系統稍後處理
return inflater.inflate(R.layout.example_fragment, container, false);
}
}
參數說明:
R.layout.example_fragment:佈局資源 ID。container:父 ViewGroup(來自 Activity 佈局),傳入可讓系統套用父佈局的 LayoutParams。false:不在 inflate 階段附加到 container,避免產生多餘 ViewGroup。<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:name="com.example.news.ArticleListFragment"
android:id="@+id/list"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />
<fragment
android:name="com.example.news.ArticleReaderFragment"
android:id="@+id/reader"
android:layout_weight="2"
android:layout_width="0dp"
android:layout_height="match_parent" />
</LinearLayout>
適用於固定不變的 UI 結構(如平板雙欄)。注意:靜態加入的 Fragment 無法在執行期移除或替換。
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
// 替換容器中的 Fragment
ft.replace(R.id.fragment_container, new DetailFragment());
// 加入回退堆疊,支援返回鍵導航
ft.addToBackStack(null);
// 提交事務
ft.commit();
關鍵重點:
addToBackStack() 將事務存入 Activity 管理的回退堆疊,使用者按返回鍵可回到上一個 Fragment 狀態。addToBackStack(),Fragment 會被銷毀且無法導航返回;若有呼叫,則會停止並保留狀態。commit() 為非同步排程,若需立即執行可呼叫 executePendingTransactions()。commit(),否則會拋出例外。getActivity() 取得宿主 Activity 實例,進而存取其 View 或方法。View listView = getActivity().findViewById(R.id.list);FragmentManager.findFragmentById() 或 findFragmentByTag() 取得 Fragment 參考,直接呼叫其 public 方法。ExampleFragment f = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment);Android SDK 的 API Demos 專案已包含完整的 Fragment 使用範例(路徑:<sdk>/samples/android-<version>/ApiDemos),涵蓋動態切換、對話框、清單、偏好設定等場景,建議直接參考原始碼,避免重複造輪子。
Fragment 是 Android 適應多裝置、多螢幕的基石。掌握其生命週期、動態事務管理、與 Activity 通訊模式,即可打造出在手機、平板、折疊裝置上都能提供最佳體驗的應用程式。善用官方 API Demos 並結合支援庫 (AndroidX Fragment),可確保向下相容與長期維護性。