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

Android Fragment 入門:概念、生命週期與使用方式

編輯:關於 Android 程式設計

Fragment 是什麼

Android 從 3.0(API Level 11)開始引入 Fragment。可以把 Fragment 想成 Activity 中的一個模塊:它有自己的版面配置、自己的生命週期,能獨立處理自己的輸入事件,並在 Activity 執行期間被動態加入或移除。

正因為它是模塊化的,Fragment 可以被設計成能在多個 Activity 之間重複使用。當同一個應用同時要跑在平板與手機上時,善用 Fragment 就能輕鬆做出彈性的版面配置,大幅改善使用者體驗。

Fragment 的生命週期

因為 Fragment 必須嵌入 Activity 中使用,兩者的生命週期緊密相關:

  • Activity 暫停時,其中所有 Fragment 也跟著暫停;
  • Activity 進入 stopped 時,其中的 Fragment 無法被啟動;
  • Activity 被銷毀時,其中的 Fragment 全部一併銷毀。

但在 Activity 處於活動狀態時,可以獨立控制各 Fragment 的狀態,例如加上或移除某個 Fragment。進行這種 fragment transaction 時,可以把 Fragment 放進 Activity 的 back stack,讓使用者得以回退。

Support Library:讓舊版本也能用

使用 Fragment 時必須繼承 Fragment 或其子類(DialogFragment、ListFragment、PreferenceFragment、WebViewFragment),因此程式碼風格與 Activity 相當類似。

Support Library 是一份提供 API 函式庫的 JAR 檔,讓舊版 Android 也能用上新版的 API,例如 android-support-v4.jar,完整路徑為:

<sdk>/extras/android/support/v4/android-support-v4.jar

它提供了 Fragment 的 API,使 Android 1.6(API Level 4)以上都能使用。為了確保不會在舊系統上誤用新 API,導入時要使用 support 版本的套件:

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。

另外,建立含 Fragment 的 Activity 時,若使用 Support Library,該 Activity 必須繼承 FragmentActivity 而非 Activity。

必須實作的三大回呼

  • onCreate():系統建立 Fragment 時呼叫。在此初始化元件,以及那些即使被暫停或停止也仍要保留的東西。
  • onCreateView():首次繪製 Fragment 的 UI 時呼叫,必須回傳一個 View;若 Fragment 不提供 UI,也可回傳 null。特別注意:若繼承自 ListFragment,此方法預設會回傳一個 ListView,就不必自己實作。
  • onPause():使用者離開 Fragment 時第一個被呼叫的方法。該提交的變更要在此提交,因為使用者很可能不會再回來。

實作 Fragment 的 UI

要提供 UI,就必須實作 onCreateView()。假設版面写在 example_fragment.xml:

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 在 Activity 中的父容器;savedInstanceState 提供上一個實例的資料。

inflate() 的三個參數

  1. resource ID:指定當前 Fragment 對應的版面資源。
  2. 父容器控制項。
  3. 布林值:是否要把該版面與其父容器連接起來。這裡必須設為 false,因為系統已經會把版面插入父容器;設為 true 會多產生一層多餘的 ViewGroup。

把 Fragment 加入 Activity

Fragment 加入 Activity 後,會處於對應的 ViewGroup 中。加入方式有兩種:在 Activity 版面中用 <fragment> 標籤宣告,或在程式碼中把它加入指定的 ViewGroup。(Fragment 也可以是完全不可見的,這部分此處先略過。)

方式一:透過版面檔宣告

<?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 提供識別的三種方式:

  1. android:id 屬性 —— 唯一的 id
  2. android:tag 屬性 —— 唯一字串
  3. 兩者都未提供時,系統改用容器 view 的 id

方式二:透過程式碼加入 ViewGroup

Activity 處於 Running 狀態時,可以動態把 Fragment 加進版面,只需指定它的父 ViewGroup:

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

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

註:若 import 的是 android.support.v4.app.FragmentManager,則要改用 getSupportFragmentManager()。add() 的第一個參數是父容器 id,最後務必呼叫 commit() 讓變更生效。

完整範例

這個練習自訂一個 Fragment 類別並寫好版面(兩個 TextView),然後分別用上述兩種方式加入同一個 Activity。

ExampleFragment.java

package com.example.learningfragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class ExampleFragment extends Fragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        System.out.println("ExampleFragment--onCreate");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        System.out.println("ExampleFragment--onCreateView");
        return inflater.inflate(R.layout.example_fragment_layout, container, false);
    }

    @Override
    public void onPause() {
        super.onPause();
        System.out.println("ExampleFragment--onPause");
    }

    @Override
    public void onResume() {
        super.onResume();
        System.out.println("ExampleFragment--onResume");
    }

    @Override
    public void onStop() {
        super.onStop();
        System.out.println("ExampleFragment--onStop");
    }
}

example_fragment_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/num1" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/num2" />
</LinearLayout>

LearnFragment.java(主 Activity)

package com.example.learningfragment;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

public class LearnFragment extends FragmentActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_learn_fragment);

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

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

activity_learn_fragment.xml

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

    <Button
        android:id="@+id/btn1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/btn1" />

    <!-- 方式一:版面宣告 -->
    <fragment
        android:name="com.example.learningfragment.ExampleFragment"
        android:id="@+id/fragment1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/btn2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/btn2" />

    <!-- 方式二:程式碼加入的目標容器 -->
    <LinearLayout
        android:id="@+id/linear"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >
        <Button
            android:id="@+id/btn3"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/btn3" />
    </LinearLayout>
</LinearLayout>

執行結果

可以看到:用方式二加入 Fragment 時,指定了父容器(一個 LinearLayout)的 id,而該容器中已有一個 Button 3,所以 Fragment 被加在按鈕之後。

參考資源

  • Fragment 類別文件:https://developer.android.com/reference/android/app/Fragment.html
  • Training: Building a Dynamic UI with Fragments
    https://developer.android.com/training/basics/fragments/index.html
  • Fragments Develop Guide:https://developer.android.com/guide/components/fragments.html
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved