編輯:關於 Android 開發
Fragment 是 Android 3.0(API 11)開始引入的元件,也是現代 Android 開發幾乎必備的知識。本文從它是什麼講起,一路談到生命週期、必要回呼與實際掛載方式。
可以把 Fragment 想成 Activity 中的一個模組:它有自己的布局、自己的生命週期,能獨立處理輸入事件,並在 Activity 執行期間被動態加入或移除。由於它足夠獨立,同一個 Fragment 可以被設計成在多個 Activity 中重複使用。
當 App 同時要支援平板與手機時,Fragment 特別好用——同一套邏輯,在平板上並排顯示,在手機上改為分頁切換,靈活度遠勝單一 Activity。

Fragment 必須依附在 Activity 上使用,因此兩者的生命週期緊密相關。Activity 進入 paused,其中所有 Fragment 也 paused;Activity 進入 stopped,其中的 Fragment 無法啟動;Activity 被銷毀,Fragment 同樣被銷毀。
但在 Activity 處於活動狀態時,你可以獨立控制 Fragment 的狀態,例如動態加入或移除。進行 fragment transaction 時,還可以把 Fragment 放進 Activity 的 back stack,讓使用者能透過返回鍵還原上一個狀態。

使用 Fragment 時必須繼承 Fragment 或其子類(DialogFragment、ListFragment、PreferenceFragment、WebViewFragment),整體寫法與 Activity 相當類似。
Support Library 提供了一組 API 庫,讓舊版本 Android 也能用上新 API。其中的 android-support-v4.jar 就包含 Fragment 的實作,使得 Android 1.6(API 4)以上都能使用 Fragment。完整路徑為:
<sdk>/extras/android/support/v4/android-support-v4.jar
為了確保在舊系統上不會誤用新 API,匯入時要明確指定套件:
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
同時把 jar 放進專案的 libs 目錄,並在專案 Properties 中補上:右鍵專案 → Properties → Java Build Path → Add External JARs,選入 android-support-v4.jar。

關鍵提醒:如果採用 Support Library,包含 Fragment 的 Activity 必須繼承 FragmentActivity,而不是 Activity。
onCreate():系統建立 Fragment 時呼叫,適合在這裡初始化元件,以及那些即使被暫停或停止也仍需保留的狀態。
onCreateView():第一次繪製 UI 時呼叫,必須回傳一個 View;若 Fragment 不提供 UI,也可以回傳 null。特別注意,若繼承自 ListFragment,預設實作已會回傳一個 ListView,就不必自己寫了。
onPause():使用者離開 Fragment 時第一個被呼叫,該提交的變更要在此提交,因為使用者很可能不會再回來。
提供 UI 就必須實作 onCreateView()。假設布局寫在 example_fragment.xml:
public static class ExampleFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.example_fragment, container, false);
}
}
其中 container 代表這個 Fragment 在 Activity 中的父容器;savedInstanceState 提供上一個實例的資料。
inflate() 的三個參數:第一個是資源 ID,指明對應的布局檔;第二個是父容器;第三個 boolean 表示是否把該布局與父容器連接。這裡必須填 false,因為系統已經會把布局插入父容器,填 true 會多產生一層無用的 ViewGroup。
Fragment 加入 Activity 後,會處於對應的 ViewGroup 之中。加入方式有兩種:在布局檔中用 <fragment> 標籤宣告,或在程式碼中動態加入指定的 ViewGroup。(Fragment 也可以完全獨立於 Activity 布局之外,成為不可見的元件,這部分先略過。)
方式一:透過布局檔宣告
<?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 提供 ID 有三種方式:android:id(唯一 id)、android:tag(唯一字串),若兩者都沒給,系統會採用容器 view 的 ID。
方式二:透過程式碼動態加入
Activity 處於執行狀態時,可以在布局中動態加入 Fragment,只要指定父 ViewGroup 即可。先取得 FragmentTransaction:
FragmentManager fragmentManager = getFragmentManager()
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
(若匯入的是 android.support.v4.app.FragmentManager,則要改用 getSupportFragmentManager()。)
接著用 add() 加入 Fragment 物件:
ExampleFragment fragment = new ExampleFragment();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();
add() 的第一個參數是這個 Fragment 的容器,也就是父 ViewGroup。最後一定要呼叫 commit(),改動才會真正生效。
Android 建立 SQLite 資料庫的步驟
Android 建立 SQLite 資料庫的步驟在 Android 中建立 SQLite 資料庫,通常會使用 SQLiteOpenHelper。這個輔助類別可以協助開發者
ListView 入門實戰:SimpleAdapter 綁定數據與 item 點擊事件
ListView 入門實戰:從數據綁定到點擊響應 ListView 是 Android 早期最基礎的列表組件。本文用一個包含圖標、標題和描述的完整示例,把 SimpleA
為 Android 影片播放器加上 SeekBar 進度條與拖動跳轉
為 Android 影片播放器加上 SeekBar 進度條與拖動跳轉 在既有的 SurfaceView 影片播放器專案中,我們可以再加上一個 SeekBar,讓使用者能即
Android 高效計算:RenderScript 入門(一)基本概念與工作流程
Android 高效計算:RenderScript 入門(一)基本概念與工作流程 高效計算 —— RenderScript RenderScript 是 Google 在