Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Fragment 基礎完整講解:生命週期、事務管理與 Activity 通信

編輯:關於 Android 程式設計

Fragment 代表 Activity 中的一個 UI 行為,或畫面的一部分。你可以把多個 Fragment 組合在一個 Activity 裡,構成多區域的介面,也能讓同一個 Fragment 在多個 Activity 之間重用。與其把它看成一個「迷你 Activity」,不如理解為 Activity 的模組化單元:它有自己的生命週期、接收屬於自己的輸入事件,並且可以在 Activity 運行期間被動態加入或移除。

Fragment 必須依附於某個 Activity 存在,其生命週期直接受宿主 Activity 影響:Activity 暫停時,內部所有 Fragment 一起暫停;Activity 被銷毀時,所屬 Fragment 也一併銷毀。但在 Activity 處於 resumed 狀態期間,你可以獨立地操作每一個 Fragment,例如加入或刪除。處理這類變更時,還可以把它記錄到 Activity 管理的返回堆疊(back stack)中——每一筆記錄就是一次發生過的 Fragment 事務,使用者按 BACK 鍵即可逐筆回退。

作為 Activity 佈局的一部分時,Fragment 位於 Activity 的 view hierarchy 中的某個 ViewGroup 裡,並擁有自己的一套視圖。你可以直接在佈局檔中宣告它,也可以用程式碼動態加入既有的 ViewGroup。Fragment 甚至不必是佈局的一部分——它也可以作為沒有 UI 的後台工作者存在。

設計哲學

Fragment 在 Android 3.0 引入,主要目標是服務大螢幕裝置(如平板),以支援更動態、更靈活的 UI 設計。平板螢幕比手機大得多,能容納更多 UI 元件,元件之間的交互也更多。Fragment 讓這種設計變得可行,同時免去了你自己管理複雜 view hierarchy 變更的負擔:把 Activity 的佈局拆分到各 Fragment 中,就能在執行期修改 Activity 的外觀,並把這些變化保存在返回堆疊裡。

舉個經典例子:新聞應用可以在左側用一個 Fragment 展示文章列表,右側用另一個 Fragment 展示文章內容。兩個 Fragment 並排在同一个 Activity 中,各自擁有生命週期回呼、各自處理自己的輸入事件。使用者就在同一個畫面完成「選文章 → 讀文章」,不必在兩個 Activity 之間跳轉。

因此,Fragment 應當被設計成模組化、可重用的元件。由於它自帶佈局與行為,可以嵌入多個 Activity,這讓你能夠依螢幕尺寸調整使用者體驗:螢幕夠大時,一個 Activity 放兩個 Fragment;不夠大時,只放列表 Fragment,使用者點選後再啟動另一個只含閱讀 Fragment 的 Activity。同一套 Fragment,兩種形態。

建立 Fragment

要建立 Fragment,需繼承 Fragment 類(或其既有子類)。Fragment 的程式碼結構與 Activity 相當相似,包含 onCreate()、onStart()、onPause()、onStop() 等回呼。事實上,若要把既有應用改造成使用 Fragment,多數時候只是把 Activity 回呼裡的程式碼搬進對應的 Fragment 回呼。

至少需要實作的這三個方法:

onCreate()
Fragment 建立時由系統呼叫。在這裡初始化那些「被暫停或停止後仍需恢復」的必要元件。

onCreateView()
Fragment 首次繪製 UI 時呼叫。此方法必須回傳一個 View,作為 Fragment 佈局的根視圖;若 Fragment 不提供 UI,可回傳 null。

onPause()
使用者即將離開 Fragment 時收到的第一個訊號(但不等於 Fragment 一定會被銷毀)。凡是必須持久化的變更,通常應在此提交,因為使用者未必會回來。

除了這三個,還有若干回呼可用來處理生命週期的其他階段,後文會一併說明。

另外,除了直接繼承 Fragment,還有幾個常用子類:

DialogFragment:顯示浮動對話框。相較於 Activity 的對話框工具方法,它的優勢在於可以把對話框併入 Activity 管理的返回堆疊,讓使用者能回到先前關閉的對話框。

ListFragment:顯示由 Adapter(如 SimpleCursorAdapter)管理的列表,類似 ListActivity,並提供 onListItemClick() 等回呼來處理點擊。

PreferenceFragment:以階層列表顯示 Preference 物件,類似 PreferenceActivity,適合製作應用的「設定」頁面。

為 Fragment 加上使用者介面

Fragment 通常作為 Activity UI 的一部分,並把自己的佈局提供給 Activity。要提供佈局,就必須實作 onCreateView(),並回傳 Fragment 佈局的根視圖。

註:若你的 Fragment 是 ListFragment 子類,其預設實作會回傳一個 ListView,通常不必自行覆寫。

onCreateView() 會提供一個 LayoutInflater,方便你直接從 XML 佈局資源 inflate 出視圖:

public static class ExampleFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // 為此 Fragment 載入佈局
        return inflater.inflate(R.layout.example_fragment, container, false);
    }
}

傳入的 container 是 Fragment 佈局將被插入的父 ViewGroup(來自 Activity 佈局),savedInstanceState 則在 Fragment 被恢復時提供先前實例的資料。

inflate() 的三個參數:

1. 要載入的佈局資源 ID;
2. 佈局的父 ViewGroup。傳入 container 很重要,系統需要它才能正確解析根視圖的 LayoutParams;
3. 一個 boolean,表示載入期間是否把展開後的佈局附加到 ViewGroup。這裡傳 false,因為系統已經會把佈局插入 container,傳 true 會多出一層無用的 ViewGroup。

把 Fragment 加入 Activity

有兩種方式。

方式一:在 Activity 佈局檔中宣告

Fragment 可以像普通 View 一樣在 XML 中指定佈局屬性:

<?xml version="1.0" encoding="utf-8"?>
<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/viewer"
        android:layout_weight="2"
        android:layout_width="0dp"
        android:layout_height="match_parent" />

</LinearLayout>

android:name 指定要在佈局中建立的 Fragment 類。系統在構建 Activity 佈局時,會建立每個 Fragment 並呼叫其 onCreateView() 取得視圖,然後直接插入到 <fragment> 標籤所在的位置。

注意:每個 Fragment 都需要一個唯一標識,以便 Activity 重啟時恢復它(也方便你在程式碼中捕獲它來處理事務,例如移除)。提供標識有三種方式:

· 為 android:id 提供唯一 ID;
· 為 android:tag 提供唯一字串;
· 兩者都未提供時,系統使用容器視圖的 ID。

方式二:用程式碼加入既有 ViewGroup

Activity 運行的任何時刻都能加入 Fragment,只需指定要放入的 ViewGroup。所有這類操作(加入、移除、替換)都要透過 FragmentTransaction 的 API 完成:

FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

ExampleFragment fragment = new ExampleFragment();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();

add() 的第一個參數是 Fragment 要放入的 ViewGroup(以資源 ID 指定),第二個是要加入的 Fragment。改動做完後,必須呼叫 commit() 才會生效。

加入一個沒有 UI 的 Fragment

前面的例子都涉及 UI。但你也可以用 Fragment 為 Activity 提供後台行為,而不顯示任何額外介面。

做法是用 add(Fragment, String),傳入一個唯一 tag 字串而非視圖 ID。由於沒有關聯到佈局中的任何視圖,它不會收到 onCreateView() 回呼,因此不必實作該方法。

提供 tag 並非無 UI 的 Fragment 專屬——有 UI 的也可以有 tag;但對無 UI 的 Fragment 而言,tag 是識別它的唯一途徑。之後若要取回它,需用 findFragmentByTag()。

管理 Fragment

管理 Fragment 需要 FragmentManager,透過 Activity 的 getFragmentManager() 取得。它能做的事包括:

· 用 findFragmentById()(適合佈局中有 UI 的 Fragment)或 findFragmentByTag()(有沒有 UI 都適用)取得 Activity 中的 Fragment;
· 用 popBackStack() 把 Fragment 從返回堆疊彈出,模擬使用者按 BACK;
· 用 addOnBackStackChangeListener() 註冊監聽返回堆疊變化的 listener。

處理 Fragment 事務

Fragment 最強的一點,是能依使用者交互動態地加入、移除、替換。每一組提交給 Activity 的變化稱為一個「事務」,由 FragmentTransaction 的 API 處理;你也可以把每個事務保存到 Activity 管理的返回堆疊,讓使用者能像 Activity 之間回退那樣,在 Fragment 變化之間往回導航。

FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

每個事務是一組要一起執行的變化。你可以先設定好所有變化(add()、remove()、replace()),最後呼叫 commit() 套用。

在 commit() 之前呼叫 addToBackStack(),就能把事務存進返回堆疊,讓使用者按 BACK 回到前一個狀態:

// 建立新的 Fragment 與事務
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();

// 用這個 Fragment 替換 fragment_container 中的內容,
// 並把事務加入返回堆疊
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);

// 提交事務
transaction.commit();

這裡 newFragment 替換了容器中原本由 R.id.fragment_container 標識的 Fragment。因為呼叫了 addToBackStack(),replace 事務被保存下來,使用者按 BACK 就能回到替換前的狀態。

若在一個事務中加入了多個變化(例如連續的 add 或 remove)並呼叫 addToBackStack(),那麼在 commit() 之前套用的所有變化會被視為單一事務存入堆疊,一次 BACK 全部回退。

加入變化的順序一般不重要,但有兩個例外:

· commit() 必須最後呼叫;
· 若往同一個容器加入多個 Fragment,加入順序決定它們在 view hierarchy 中的顯示順序。

還有一點值得留意:執行移除 Fragment 的事務時,若沒有呼叫 addToBackStack(),事務提交後該 Fragment 會被銷毀,使用者無法回到它;反之若呼叫了,Fragment 只是被停止,使用者回退時它會被恢復。

提示:每個事務都可以套用轉場動畫,在提交前呼叫 setTransition() 即可。

另外要理解 commit() 的 semantics:它不會立即執行事務,而是排入排程,等就緒後在 Activity 的 UI 線程(主線程)上運行。若確有必要,你可以從 UI 線程呼叫 executePendingTransactions() 立刻執行已提交的事務,但一般不需要,除非該事務是其他線程中某個 job 的前置條件。

警告:只能在 Activity 保存狀態(即使用者即將離開)之前呼叫 commit()。試圖在此之後提交會拋出例外,因為若 Activity 需要被恢復,提交後的狀態可能遺失。若你確定這種情況下遺失無妨,可改用 commitAllowingStateLoss()。

與 Activity 通信

雖然 Fragment 是獨立於 Activity 的物件、可在多個 Activity 中複用,但具體的 Fragment 實例是直接綁定到宿主 Activity 的。Fragment 可以用 getActivity() 取得 Activity 實例,進而執行諸如在 Activity 佈局中查找視圖這類任務:

View listView = getActivity().findViewById(R.id.list);

反過來,Activity 也能透過 FragmentManager 取得 Fragment 引用,再呼叫其中的方法:

ExampleFragment fragment = (ExampleFragment)
        getFragmentManager().findFragmentById(R.id.example_fragment);

為 Activity 定義事件回呼

某些時候 Fragment 需要把事件分享給 Activity。良好的做法是在 Fragment 中定義一個回呼介面,並要求宿主 Activity 實作它。Activity 收到回呼後,可以按需要把資訊轉發給佈局中的其他 Fragment。

例如某應用的 Activity 中有兩個 Fragment:Fragment A 顯示文章列表,Fragment B 顯示文章內容。Fragment A 必須告訴 Activity「哪一項被選中了」,Activity 再通知 Fragment B 去載入對應內容。

Fragment A 中宣告的介面:

public static class FragmentA extends ListFragment {
    ...
    // 宿主 Activity 必須實作此介面
    public interface OnArticleSelectedListener {
        public void onArticleSelected(Uri articleUri);
    }
    ...
}

宿主 Activity 實作該介面並覆寫 onArticleSelected()。為了確保 Activity 確實實作了,Fragment A 會在 onAttach() 回呼(Fragment 被加入 Activity 時由系統呼叫)中把傳入的 Activity 轉型為該介面:

public static class FragmentA extends ListFragment {

    OnArticleSelectedListener mListener;
    ...

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnArticleSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnArticleSelectedListener");
        }
    }
    ...
}

若 Activity 沒有實作,Fragment 會拋出 ClassCastException——這是刻意設計的「早失敗」,避免問題被推到更難查的地方才爆發。

平時 mListener 持有對 Activity 實作的引用,Fragment A 即可透過介面方法把事件傳出去。以 ListFragment 為例,每次點擊列表項時系統呼叫 onListItemClick(),再由它轉發給 Activity:

public static class FragmentA extends ListFragment {

    OnArticleSelectedListener mListener;
    ...

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        // 把被點擊項的 row ID 附加到 ContentProvider 的 Uri 上
        Uri noteUri = ContentUris.withAppendedId(ArticleColumns.CONTENT_URI, id);
        // 把事件與 Uri 交給宿主 Activity
        mListener.onArticleSelected(noteUri);
    }
    ...
}

傳給 onListItemClick() 的 id 是被點擊項的 row ID,Activity(或其他 Fragment)可用它從 ContentProvider 取得文章內容。

為 Action Bar 加上項目

Fragment 可以透過實作 onCreateOptionsMenu() 為 Activity 的選項菜單(以及 Action Bar)提供項目。但要讓這個回呼被呼叫,必須在 onCreate() 中呼叫 setHasOptionsMenu(true) 表明 Fragment 願意貢獻菜單項,否則它收不到回呼。

Fragment 加入的菜單項會追加在既有項之後。當某個項目被選中,Fragment 也會收到 onOptionsItemSelected() 回呼。此外,你也可以在 Fragment 佈局中呼叫 registerForContextMenu() 為某個視圖註冊情境菜單;使用者打開時 Fragment 收到 onCreateContextMenu(),選項被點選時收到 onContextItemSelected()。

注意:雖然 Fragment 會收到「自己加入的每個菜單項被選中」的回呼,但實際上使用者選擇時,Activity 會先收到回呼。只有在 Activity 的實作沒有消費該事件時,才會往下傳給 Fragment 的回呼。這條規則對選項菜單與情境菜單都適用。

Fragment 的生命週期

Fragment 與 Activity 一樣,可以處於三種狀態:

Resumed:Fragment 在運行中的 Activity 裡可見。
Paused:另一個 Activity 位於前台並擁有焦點,但 Fragment 所在的 Activity 仍部分可見(例如前台 Activity 是半透明或未覆蓋整個螢幕)。
Stopped:宿主 Activity 已被停止,或 Fragment 已從 Activity 移除但被加入返回堆疊。

處於 Stopped 的 Fragment 仍然活著(系統保留其所有狀態與成員資訊),只是對使用者不可見;若 Activity 被回收,它也會一起消失。

同樣地,你可以用 Bundle 保存 Fragment 狀態,以防 Activity 進程被回收後需要恢復。保存時機是 onSaveInstanceState(),恢復則可在 onCreate()、onCreateView() 或 onActivityCreated() 中進行。

在生命週期上,Activity 與 Fragment 最重要的差異在於返回堆疊的處理方式:Activity 默認會被系統放入由系統管理的堆疊(因此使用者能用 BACK 回到它);而 Fragment 只有在你移除它並顯式呼叫 addToBackStack() 請求保存時,才會被放進由宿主 Activity 管理的堆疊。

除此之外,兩者的管理思路高度相似,Activity 生命週期的相關實踐基本都適用於 Fragment。你真正需要掌握的是:Activity 的生命如何牽動 Fragment 的生命。

與宿主 Activity 生命週期的協調

Activity 的每個生命週期回呼,都會引起其中各 Fragment 的對應回呼。例如 Activity 收到 onPause() 時,其中每個 Fragment 也會收到 onPause()。

此外,Fragment 有幾個專屬回呼,用於處理與 Activity 之間獨有的交互,主要圍繞 Fragment 自身 UI 的建立與銷毀:

onAttach():Fragment 被綁定到 Activity 時呼叫(Activity 作為參數傳入)。
onCreateView():建立與 Fragment 關聯的視圖階層時呼叫。
onActivityCreated():Activity 的 onCreate() 返回後呼叫。
onDestroyView():與 Fragment 關聯的視圖階層被移除時呼叫。
onDetach():Fragment 與 Activity 解除關聯時呼叫。

把這些回呼排成一條時間線,就能看出 Activity 的每個狀態如何決定 Fragment 能收到的回呼。例如 Activity 收到 onCreate() 時,其中的 Fragment 最多只會走到 onActivityCreated()。

一旦 Activity 進入 resumed 狀態,你就可以自由地在其中加入與移除 Fragment。也就是說,只有在 Activity 處於 resumed 狀態時,Fragment 的生命週期才能獨立變化;當 Activity 離開該狀態,Fragment 又會重新被 Activity 帶著走它自己的流程。

實務上有兩個高頻陷阱值得記住:一是 onDestroyView() 與 onDestroy() 的區別——Fragment 在返回堆疊中被替換時只會走到 onDestroyView(),此時必須解除視圖相關的引用(例如 Handler、監聽器、資料 Binding),否則容易洩漏;二是不要在 onCreateView() 裡做耗時操作,它會直接拖慢頁面顯示。

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