Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 進階開發

Android Fragment 片段:模組化 UI 與生命週期指南

編輯:進階開發

Fragment(片段)代表應用程式中的一塊使用者介面或行為,目的是讓 Activity 的設計更模組化、可以拆解重組。你可以把它理解成一種「子 Activity」。關於 Fragment,有幾個重點要先掌握:

  • 每個 Fragment 都有自己的版面配置,也能管理自己的行為與生命週期回呼。
  • Fragment 可以在 Activity 執行期間被動態加入或移除。
  • 多個 Fragment 可以並存在同一個 Activity 中,組成多窗格(multi-pane)介面。
  • 同一個 Fragment 可以被多個 Activity 重複使用。
  • Fragment 的生命週期與宿主 Activity 緊密相連:Activity 暫停時,其中的 Fragment 也會跟著停止。
  • Fragment 也可以在不提供任何 UI 的情況下,單純承載某段行為邏輯。
  • Fragment 自 Android Honeycomb(API 11)起被納入官方 API。

建立 Fragment 的方式是繼承 Fragment 類別;若要把它宣告在版面中,則於 Activity 的配置檔裡使用 <fragment> 元素插入。

在 Fragment 出現之前,Android 有個先天限制:同一時間點螢幕上只能顯示單一 Activity,因此無法把畫面切開、各自獨立運作。Fragment 的導入打破了這個限制——畫面上仍只有一個 Activity,但它可以容納多個 Fragment,每個 Fragment 都有自己的版面、邏輯與完整生命週期。

下面是一個很典型的應用情境:兩個 UI 模組以 Fragment 形式定義,在平板裝置上組合成單一 Activity,而在手機上則拆成兩個畫面。

在平板尺寸的裝置上,Activity A 同時嵌入這兩個 Fragment;但在手機螢幕上空間不足,於是 Activity A 只顯示文章清單那個 Fragment,使用者點選某篇文章後,才啟動 Activity B 來顯示內容 Fragment。

Fragment 生命週期

Fragment 的生命週期與 Activity 相當類似,可以拆成幾個階段來看。

階段一:建立——Fragment 被建立時依序經過:

  • onAttach()
  • onCreate()
  • onCreateView()
  • onActivityCreated()

階段二:可見——Fragment 出現在使用者面前:

  • onStart()
  • onResume()

階段三:退到背景——Fragment 進入背景模式:

  • onPaused()
  • onStop()

階段四:銷毀——Fragment 被破壞:

  • onPaused()
  • onStop()
  • onDestroyView()
  • onDestroy()
  • onDetach()

怎麼使用 Fragment?

實作流程可以濃縮成四步:

  • 先想清楚這個 Activity 需要幾個 Fragment。例如要分別處理裝置的橫向與縱向模式,就需要兩個。
  • 依數量建立類別,每個都繼承 Fragment 類別,並視需要覆寫前述的生命週期回呼。
  • 為每個 Fragment 準備一份 XML 版面檔,用來定義它的外觀。
  • 最後修改 Activity,把實際的切換邏輯寫進去。

以下三個方法是最常被覆寫的:

  • onCreate():Fragment 建立時由系統呼叫,適合初始化那些在你暫停或停止後仍需保留的狀態。
  • onCreateView():Fragment 第一次繪製介面時呼叫。若要為 Fragment 提供 UI,就必須在這裡回傳一個 View 作為它的根配置;回傳 null 則代表這個 Fragment 沒有畫面。
  • onPause():系統第一次暗示使用者即將離開這個 Fragment 時呼叫,通常用來提交那些需要比對話延續更久的變更。

實作範例

接下來建立一個名為 MyFragments 的範例,包含兩個 Fragment,並依裝置方向自動切換:橫向時用一個,縱向時用另一個。

步驟說明
1用 Eclipse IDE 建立 Android 專案 MyFragments,套件 com.example.myfragments,使用空白 Activity。
2修改 MainActivity.java,加入方向判斷與 Fragment 切換邏輯。
3在 com.example.myfragments 下建立 LM_Fragment.java 與 PM_Fragment.java。
4建立 res/layout/lm_fragment.xml 等版面檔。
5修改 res/layout/activity_main.xml,放入 Fragment。
6在 res/values/strings.xml 定義所需常數。
7執行應用程式並驗證結果。

以下是 MainActivity.java 的內容:

 package com.example.myfragments; import android.os.Bundle; import android.app.Activity; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.content.res.Configuration; import android.view.WindowManager; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Configuration config = getResources().getConfiguration(); FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); /** * Check the device orientation and act accordingly */ if (config.orientation == Configuration.ORIENTATION_LANDSCAPE) { /** * Landscape mode of the device */ LM_Fragment ls_fragment = new LM_Fragment(); fragmentTransaction.replace(android.R.id.content, ls_fragment); }else{ /** * Portrait mode of the device */ PM_Fragment pm_fragment = new PM_Fragment(); fragmentTransaction.replace(android.R.id.content, pm_fragment); } fragmentTransaction.commit(); } }

接著是兩個 Fragment 類別。LM_Fragment.java:

 package com.example.myfragments; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class LM_Fragment extends Fragment{ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { /** * Inflate the layout for this fragment */ return inflater.inflate( R.layout.lm_fragment, container, false); } }

PM_Fragment.java:

 package com.example.myfragments; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class PM_Fragment extends Fragment{ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { /** * Inflate the layout for this fragment */ return inflater.inflate( R.layout.pm_fragment, container, false); } }

兩個版面檔放在 res/layout 下。lm_fragment.xml:

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#7bae16"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/landscape_message" android:textColor="#000000" android:textSize="20px" /> <!-- More GUI components go here --> </LinearLayout>

pm_fragment.xml:

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#666666"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/portrait_message" android:textColor="#000000" android:textSize="20px" /> <!-- More GUI components go here --> </LinearLayout>

activity_main.xml 則以 <fragment> 元素放入片段:

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="horizontal"> <fragment android:name="com.example.fragments" android:id="@+id/lm_fragment" android:layout_weight="1" android:layout_width="0dp" android:layout_height="match_parent" /> <fragment android:name="com.example.fragments" android:id="@+id/pm_fragment" android:layout_weight="2" android:layout_width="0dp" android:layout_height="match_parent" /> </LinearLayout>

最後確認 res/values/strings.xml 的內容:

 <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">MyFragments</string> <string name="action_settings">Settings</string> <string name="hello_world">Hello world!</string> <string name="landscape_message">This is Landscape mode fragment </string> <string name="portrait_message">This is Portrait mode fragment </string> </resources>

執行與切換方向

現在執行剛建立的 MyFragments。請確認 AVD 與環境都已設定好,開啟專案 Activity 檔並點擊工具列上的「Run」 圖示。Eclipse 會把 App 裝上 AVD 並啟動,模擬器視窗如下,可能需要按一下「MENU」鈕(首次啟動會稍慢,請依電腦效能耐心等候):

要旋轉模擬器畫面,可以:

  • Mac 上用 fn + control + F11
  • Windows 上用 ctrl + F11
  • Linux 上用 ctrl + F11

切換方向之後,畫面就會換成另一個 Fragment 呈現的介面。以下就是橫向模式的結果:

如此一來,同一個 Activity 就能依情境套用不同的 GUI,而差異完全封裝在各自的 Fragment 裡。只要更換 Fragment 的實作,就能組合出各式各樣的畫面。

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