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

Android Fragment 完全指南:生命週期、事務管理與 Activity 通訊

編輯:關於 Android 程式設計

Fragment 是 Activity 界面中的一部分,也是一種可獨立描述的行为單元。把多個 Fragment 組進同一個 Activity,就能拼出一個多面板的複合界面;而同一個 Fragment 又能在多個 Activity 之間重用。你可以把它理解為「模組化的一段 Activity」——擁有自己的生命週期、接收自己的事件,並能在宿主 Activity 執行期間被動態加入或移除。

基本定位

Fragment 無法獨立存在,必須依附在 Activity 之內,其生命週期直接受宿主影響:Activity 暫停時,它擁有的所有 Fragment 一起暫停;Activity 銷毀時,Fragment 也隨之銷毀。不過在 Activity 處於 running 狀態(onResume 之後、onPause 之前)時,你可以自由對每個 Fragment 做增刪操作。

這些針對 Fragment 的操作可以打包進一個由 Activity 管理的堆疊,堆疊中每一筆就是一次 Fragment 事務。有了這個堆疊,就能反向回放事務,等於在 Fragment 層級支援了「返回鍵」的導航能力。

加入 Activity 時,Fragment 必須置於某個 ViewGroup 容器裡並提供自己的界面。你可以在布局 XML 中直接以 fragment 標籤宣告,也可以在程式碼中建立後加進 ViewGroup。值得一提的是,Fragment 並非一定要佔用畫面——它完全可以隱身在背後為 Activity 做事。

設計哲學:為什麼要有 Fragment

Android 從 3.0 開始引入 Fragment,主要目的是支援更動態、更靈活的界面設計,尤其是平板這類大螢幕裝置。平板的螢幕空間足以同時並置多個功能區塊,而 Fragment 讓你不必去應付 view 樹龐雜的結構變換:把 Activity 的布局切成幾個 Fragment,就能在執行期任意替換,並把這些改變保存進返回堆疊。

以新聞閱讀器為例:用一個 Fragment 顯示標題列表,另一個顯示所選標題的內容,兩者並排在同一個 Activity 上,各自擁有自己的生命週期與事件回應。對比手機版的舊做法——一個 Activity 顯示列表、另一個 Activity 顯示內容——差別一目了然。

因此,Fragment 從一開始就應該被寫成可重用的模組。正因為它自帶布局、自帶事件回應、自帶生命週期與行為,同一個 Fragment 才能在不同 Activity 中以不同實例出現。這對適配多種螢幕尺寸尤其重要:大螢幕時啟動一個裝了多個 Fragment 的 Activity,小螢幕時則啟動只裝少量 Fragment 的 Activity。

回到剛才的例子——偵測到大螢幕時啟動 ActivityA,把標題列表與內容兩個 Fragment 都放進去;偵測到小螢幕時同樣啟動 ActivityA,但裡頭只放標題列表,使用者點選標題後再由 A 去啟動帶著內容 Fragment 的 ActivityB。

建立 Fragment

要建立 Fragment,必須繼承 Fragment 或其派生類別。它的寫法與 Activity 頗為相似,同樣具備 onCreate()、onStart()、onPause()、onStop() 這類回呼。幾個特別值得記住的方法:

  • onCreate():初始化資源,此時尚未具備界面。
  • onCreateView():建立並回傳 Fragment 的布局 View。
  • onActivityCreated():Activity 的 onCreate 執行完畢後呼叫,適合在這裡處理需要宿主已就緒的初始化。
  • onPause():與 Activity 對應。
  • onDestroyView():布局被銷毀時呼叫,與 onCreateView 成對。
  • onDetach():Fragment 從 Activity 分離時呼叫。

系統另外提供了幾個現成的派生類別,視需求可從它們著手:

DialogFragment——顯示浮動對話框。用它取代 Activity 來管理對話框是更好的選擇,因為對話框可以進到返回堆疊,使用者能再返回該對話框。

ListFragment——顯示列表控制項,性質近似 ListActivity,並已內建 onListItemClick() 等便利方法。

PreferenceFragment——顯示由 Preference 物件組成的清單,與 PreferenceActivity 相同,通常用於建立「設定」頁面。

為 Fragment 加上界面

Fragment 一般作為 Activity 界面的一部分,把自己的布局嵌入宿主的布局中。做法是實作 onCreateView() 並回傳該布局的根 View。若你的 Fragment 繼承自 ListFragment,則可略過這一步——預設實作已為你回傳一個 ListView。

onCreateView() 貼心地提供了一個 LayoutInflater 參數,省去自行取得的麻煩:

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;savedInstanceState 則是狀態回復用的 Bundle。注意 Fragment 的 onCreate() 也有 Bundle 參數,兩者存放的內容並不相同,別搞混了。

把 Fragment 加入 Activity

有兩種方式。

方式一:在布局 XML 中宣告

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <fragment android:id="@+id/list"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:name="com.example.news.ArticleListFragment" />

    <fragment android:id="@+id/viewer"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="2"
        android:name="com.example.news.ArticleReaderFragment" />
</LinearLayout>

系統在載入這份布局時,會逐一實例化每個 Fragment、呼叫它們的 onCreateView() 取得布局,再把回傳的 View 直接放回標籤所在的位置。

每個 Fragment 都需要一個 ID,用途有二:Activity 重建時據以回復,以及後續程式操作時的參照。提供 ID 有三種方式——為 android:id 指定數字資源、為 android:tag 指定字串,或兩者皆不使用,此時系統會採用容器的 ID。

方式二:在程式碼中加進 ViewGroup

這種方式能在執行期動態增刪,只需指定一個作為容器的 ViewGroup:

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

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

add() 的第一個參數是容器,第二個是要加入的 Fragment。任何透過 FragmentTransaction 做的變更,都必須呼叫 commit() 才會生效。

加入沒有界面的 Fragment

如前面所說,Fragment 也可以只提供背景行為而不顯示任何畫面。做法是用 add(Fragment, String) 這個多載,傳入一個唯一字串作為 tag 而非 view ID。這類 Fragment 不必實作 onCreateView()。取出時使用 findFragmentByTag()。

tag 並不限於無界面的 Fragment,有界面的也可以用,但對無界面者而言它是唯一的識別方式。

管理 Fragment:FragmentManager

在 Activity 中呼叫 getFragmentManager() 即可取得。它能做四件事:

  1. 用 findFragmentById() 或 findFragmentByTag() 取得現存的 Fragment。
  2. 用 popBackStack() 從返回堆疊彈出 Fragment,效果等同於模擬返回鍵。
  3. 用 addOnBackStackChangedListener() 註冊監聽器,追蹤返回堆疊的變化。
  4. 開啟一個 FragmentTransaction 以執行增刪等事務。

Fragment 事務

在 Activity 中使用 Fragment 最棒的一點,就是能依使用者操作動態增刪、替換它們。提交的一組變更稱為一個「事務」,由 FragmentTransaction 執行,且可選擇存入 Activity 的返回堆疊,讓使用者能在 Fragment 變化之間導航。

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

一個事務是一組同時發生的動作,概念上近似資料庫事務。用 add()、remove()、replace() 組裝,最後以 commit() 提交。在 commit() 之前,可以呼叫 addToBackStack() 把事務存進堆疊,這樣使用者按返回鍵時就能回到事務發生前的狀態:

// 建立新的 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 這個 ViewGroup 裡原本的任何 Fragment;addToBackStack() 則讓被取代者進到堆疊,於是使用者按返回鍵時事務回溯,原本的 Fragment 又回來了。

若在一個事務裡連續呼叫多次 add()、remove() 之後才 addToBackStack(),那麼 commit() 之前的所有動作都會被視為單一事務,返回鍵一次就把它們全部反向執行。

動作之間的順序可以任意,但有兩點必須牢記:

  1. commit() 一定要最後呼叫。
  2. 加入多個 Fragment 時,顯示順序與加入順序一致(後者覆蓋前者)。

另外一個容易忽略的差異:若事務中包含刪除動作,且沒有呼叫 addToBackStack(),那麼提交後被刪的 Fragment 就直接銷毀;反之則只是進入停止狀態,返回時能被回復。

事務也可以套用動畫,在 commit() 之前呼叫 setTransition() 即可。

最後一個觀念:commit() 之後事務並不會立刻執行,而是排進 Activity 的 UI 執行緒佇列中等候。若確有必要(例如有其他執行緒在等它完成),可呼叫 executePendingTransactions() 強制立刻執行,但一般情況不該這麼做。

⚠️ 注意:只有在 Activity 處於可保存狀態(例如 running)時才能提交事務。在 onPause() 或 onStop() 之後呼叫 commit() 會拋出例外,因為此時 Fragment 狀態已可能遺失。若確實無法避免,請改用 commitAllowingStateLoss()。

與 Activity 通訊

Fragment 的實作雖獨立於 Activity,但每個 Activity 裡的都是同一個 Fragment 的不同實例。Fragment 可以透過 getActivity() 取得宿主,進而 findViewById 存取 Activity 的元件:

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

反過來,Activity 也能透過 FragmentManager 取得它包含的 Fragment:

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

讓 Activity 接收 Fragment 的事件

較好的做法是在 Fragment 中定義回呼介面,由 Activity 實作。以前面新聞程式的 FragmentA(顯示標題)與 FragmentB(顯示內容)為例,FragmentA 必須在用戶選標題時通知 Activity,再由 Activity 決定要怎麼處理——為什麼不讓 A 直接告訴 B?可以,但這樣做會讓 Fragment 喪失可重用性。只把事件告訴宿主、由宿主決定如何處置,耦合度最低。

public static class FragmentA extends ListFragment {

    // 容器 Activity 必須實作這個介面
    public interface OnArticleSelectedListener {
        void onArticleSelected(Uri articleUri);
    }
}

Fragment 加入 Activity 時會觸發 onAttach(),這裡正是檢查宿主是否實作該介面的合適位置:

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");
        }
    }
}

若宿主沒實作,就拋出 ClassCastException;成功則把 mListener 存起來,之後便能透過它與 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);
    }
}

傳入的 id 是列表中被選列的 ID,另一個 Fragment 用這個 ID 就能從 ContentProvider 取得對應內容。

把條目加入動作欄

Fragment 可以透過實作 onCreateOptionsMenu() 為 Activity 的選單與動作欄添增項目,這些項目會出現在既有選單項之後;被選取時由 Fragment 的 onOptionsItemSelected() 接手。 Fragment 也能註冊 View 以提供情境選單,觸發時走 onCreateContextMenu() 與 onContextItemSelected()。

⚠️ 但要注意優先順序:Activity 才是事件的第一接收者。只有當 Activity 對某個事件置之不理時,Fragment 才有機會收到——選單與情境選單皆然。

Fragment 的生命週期

管理 Fragment 的生命週期與管理 Activity 頗為相似。Fragment 處於三種狀態之一:

  • Resumed:Fragment 在一個執行中的 Activity 裡且可見。
  • Paused:另一個 Activity 位於最上層,但並未完全覆蓋 Fragment 所在的 Activity(例如頂層是半透明或不佔滿整個螢幕)。
  • Stopped:Fragment 不可見。可能是宿主 Activity 進入了 stopped,也可能是 Fragment 被刪除並放進了返回堆疊。此時它仍存在於記憶體中。

同樣地,Fragment 的狀態可存入 Bundle,在 Activity 重建時用來回復——於 onSaveInstanceState() 中保存,在 onCreate()、onCreateView() 或 onActivityCreated() 中讀回。

Fragment 與 Activity 在生命週期管理上最大的差異在返回堆疊:Activity 停止時由系統自動壓入系統管理的堆疊;Fragment 則是壓入由 Activity 管理的返回堆疊,且必須在刪除 Fragment 時明確呼叫 addToBackStack() 才會入堆疊。

與 Activity 生命週期的協調

Activity 直接牽動 Fragment 的生命週期——Activity 的某個回呼被觸發時,其下所有 Fragment 的對應方法也會被呼叫。例如 Activity 的 onPause() 被呼叫,所有 Fragment 的 onPause() 隨之被呼叫。

Fragment 比 Activity 多出幾個專為互動而設的回呼:

  • onAttach():Fragment 被加入 Activity 時呼叫,可在此取得宿主。
  • onCreateView():Activity 需要 Fragment 布局時呼叫。
  • onActivityCreated():Activity 的 onCreate() 返回後呼叫。
  • onDestroyView():Fragment 布局被銷毀時呼叫。
  • onDetach():Fragment 被從 Activity 移除時呼叫。

只有當 Activity 進入 resumed 狀態時,Fragment 的生命週期才能獨立運轉;其餘時間它都依附在宿主的變化之上。

一個把上述觀念全用上的完整範例

這個範例有一個 Activity,裡頭兩個 Fragment:一個列出莎劇曲目,另一個顯示所選曲目的摘要。同時示範了如何依螢幕方向切換版面。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragment_layout);
}

橫屏時使用的布局,放在 res/layout-land/fragment_layout.xml:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <fragment android:id="@+id/titles"
        android:layout_width="0px"
        android:layout_height="match_parent"
        android:layout_weight="1"
        class="com.example.android.apis.app.FragmentLayout$TitlesFragment" />

    <FrameLayout
        android:id="@+id/details"
        android:layout_width="0px"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="?android:attr/detailsElementBackground" />
</LinearLayout>

系統載入這份布局時會初始化 TitlesFragment,右側預留一個 FrameLayout 作為摘要 Fragment 的容器——目前是空的,只有使用者點了標題之後才會填入。

但並非所有螢幕都寬到能並置兩欄,所以豎屏時改用 res/layout/fragment_layout.xml:

<FrameLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment android:id="@+id/titles"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.example.android.apis.app.FragmentLayout$TitlesFragment" />
</FrameLayout>

這份布局只含 TitlesFragment,代表豎屏時只顯示標題列表;使用者選取後,程式改為啟動一個新的 Activity 來顯示摘要,而不是載入第二個 Fragment。

TitlesFragment

它繼承自 ListFragment,列表相關功能大多由父類提供。當使用者點選標題時,程式必須判斷兩種情況:同 Activity 內顯示摘要 Fragment,或啟動新 Activity。

public static class TitlesFragment extends ListFragment {
    boolean mDualPane;
    int mCurCheckPosition = 0;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setListAdapter(new ArrayAdapter<String>(getActivity(),
                android.R.layout.simple_list_item_activated_1, Shakespeare.TITLES));

        // 檢查是否存在可嵌入摘要 Fragment 的 FrameLayout
        View detailsFrame = getActivity().findViewById(R.id.details);
        mDualPane = detailsFrame != null
                && detailsFrame.getVisibility() == View.VISIBLE;

        if (savedInstanceState != null) {
            mCurCheckPosition = savedInstanceState.getInt("curChoice", 0);
        }

        if (mDualPane) {
            getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
            showDetails(mCurCheckPosition);
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("curChoice", mCurCheckPosition);
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        showDetails(position);
    }

    /** 顯示所選項目的細節:能就地顯示就用 Fragment,否則啟動新 Activity */
    void showDetails(int index) {
        mCurCheckPosition = index;

        if (mDualPane) {
            getListView().setItemChecked(index, true);

            DetailsFragment details = (DetailsFragment)
                    getFragmentManager().findFragmentById(R.id.details);
            if (details == null || details.getShownIndex() != index) {
                details = DetailsFragment.newInstance(index);
                FragmentTransaction ft = getFragmentManager().beginTransaction();
                ft.replace(R.id.details, details);
                ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                ft.commit();
            }
        } else {
            Intent intent = new Intent();
            intent.setClass(getActivity(), DetailsActivity.class);
            intent.putExtra("index", index);
            startActivity(intent);
        }
    }
}

DetailsFragment

public static class DetailsFragment extends Fragment {

    /** 建立一個顯示 index 位置文字的新實例 */
    public static DetailsFragment newInstance(int index) {
        DetailsFragment f = new DetailsFragment();
        Bundle args = new Bundle();
        args.putInt("index", index);
        f.setArguments(args);
        return f;
    }

    public int getShownIndex() {
        return getArguments().getInt("index", 0);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (container == null) {
            // 宿主布局裡沒有我們的容器,沒必要建立 view 樹
            return null;
        }

        ScrollView scroller = new ScrollView(getActivity());
        TextView text = new TextView(getActivity());
        int padding = (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, 4,
                getActivity().getResources().getDisplayMetrics());
        text.setPadding(padding, padding, padding, padding);
        scroller.addView(text);
        text.setText(Shakespeare.DIALOGUE[getShownIndex()]);
        return scroller;
    }
}

DetailsActivity

public static class DetailsActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getResources().getConfiguration().orientation
                == Configuration.ORIENTATION_LANDSCAPE) {
            // 已是橫屏,主 Activity 能就地顯示,這個 Activity 沒有存在必要
            finish();
            return;
        }

        if (savedInstanceState == null) {
            DetailsFragment details = new DetailsFragment();
            details.setArguments(getIntent().getExtras());
            getFragmentManager().beginTransaction()
                    .add(android.R.id.content, details)
                    .commit();
        }
    }
}

值得留意的是,這個 Activity 在偵測到橫屏時會主動結束自己,把舞台交還給主 Activity 去並置兩個 Fragment。這正好處理了一個真實場景:使用者原本在豎屏下看著 TitlesFragment,中途旋轉螢幕變成橫屏——此時 DetailsActivity 自我了結,畫面無縫轉換成雙欄模式,而摘要內容透過 setArguments 保存下來並未遺失。

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