萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android Fragment 完整指南:打造適應多螢幕的彈性 UI

前言

在 Android 3.0 (API Level 11) 推出後,Fragment 成為開發者構建適應不同螢幕尺寸與解析度應用的核心組件。本文將系統性介紹 Fragment 的核心概念、生命週期、建立方式、與 Activity 的互動機制,並提供實戰程式碼範例,協助您快速掌握這項關鍵技術。

為什麼需要 Fragment?

傳統上,Activity 是 UI 的基本單元。然而,隨著平板電腦、大螢幕手機、折疊裝置的普及,單一 Activity 難以同時滿足「手機上單欄顯示」與「平板上雙欄並排」的設計需求。Fragment 解決了這個痛點:它是一個模組化的 UI 片段,擁有獨立的生命週期與輸入事件處理,可動態組合進 Activity 中。

Fragment 雙欄與單欄切換示意圖

以新聞應用為例:在平板上,左側 Fragment 顯示文章列表,右側 Fragment 顯示文章內容,兩者並存于同一 Activity;在手機上,因空間有限,僅顯示列表 Fragment,點選文章後啟動新 Activity 載入內容 Fragment。這種「一碼多端」的彈性,正是 Fragment 的核心價值。

建立 Fragment 的基本步驟

Fragment 必須繼承 android.app.Fragment (或支援庫中的 androidx.fragment.app.Fragment)。其程式碼結構與 Activity 相似,包含 onCreate()、onCreateView()、onPause() 等回呼方法。遷移既有專案時,只需將 Activity 回呼中的邏輯移至對應的 Fragment 回呼即可。

常見 Fragment 子類別

  • DialogFragment:管理浮動對話框,支援加入回退堆疊,使用者可按返回鍵恢復被關閉的對話框。
  • ListFragment:內建 ListView 與 Adapter 管理,提供 onListItemClick() 等便利方法,類似 ListActivity。
  • PreferenceFragment:顯示偏好設定階層,適合建立「設定」畫面,類似 PreferenceActivity。

Fragment 生命週期詳解

Fragment 生命週期圖

開發時最常覆寫的三個核心方法:

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();
        // 儲存持久化資料(使用者可能不會返回)
    }
}
  • onCreate():Fragment 建立時呼叫,初始化非 UI 資源。
  • onCreateView():首次繪製 UI 時呼叫,必須回傳根 View(或無 UI 時回傳 null)。
  • onPause():使用者即將離開 Fragment 時呼叫,適合提交必須持久化的變更。

載入佈局:onCreateView() 實戰

透過 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。

將 Fragment 加入 Activity 的兩種方式

1. 靜態宣告於 XML 佈局

<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 無法在執行期移除或替換。

2. 動態新增/替換 (FragmentTransaction)

FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();

// 替換容器中的 Fragment
ft.replace(R.id.fragment_container, new DetailFragment());
// 加入回退堆疊,支援返回鍵導航
ft.addToBackStack(null);
// 提交事務
ft.commit();

關鍵重點:

  • addToBackStack() 將事務存入 Activity 管理的回退堆疊,使用者按返回鍵可回到上一個 Fragment 狀態。
  • 若移除 Fragment 時未呼叫 addToBackStack(),Fragment 會被銷毀且無法導航返回;若有呼叫,則會停止並保留狀態。
  • commit() 為非同步排程,若需立即執行可呼叫 executePendingTransactions()。
  • 警告:只能在 Activity 狀態儲存前(使用者離開前)呼叫 commit(),否則會拋出例外。

Fragment 與 Activity 通訊

  • Fragment → Activity:呼叫 getActivity() 取得宿主 Activity 實例,進而存取其 View 或方法。
    View listView = getActivity().findViewById(R.id.list);
  • Activity → Fragment:透過 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),可確保向下相容與長期維護性。

copyright © 萬盛學電腦網 all rights reserved