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

Android Fragment 完全指南:生命週期、靜態與動態使用、常用 API 一次講清

編輯:關於 Android 開發

曾經有段時間,好像聊什麼都能扯到 Fragment,做什麼都要先問一句「Fragment 能不能實現」。玩笑歸玩笑,它確實是理解 Android 適配的一把鑰匙。這篇文章試著把 Fragment 從誕生、生命週期到日常用法一次講完。

一、Fragment 為什麼出現

Android 跑在手機、平板、電視等各種尺寸的裝置上。過去面對這種差異,常見做法是先做一套手機版 App,再複製一份改佈局去適配大屏——維護成本直接翻倍。Fragment 就是為了終結這種複製貼上而生的。

你可以把 Fragment 想成 Activity 介面上的一個組成單元,一整個 Activity 的畫面甚至可以完全由多個 Fragment 拼裝而成。更關鍵的是,每個 Fragment 擁有自己的生命週期、能獨立接收並處理使用者事件,不必把一堆控件的監聽器全塞進 Activity;而且 Fragment 可以動態加入、替換、移除。

二、Fragment 的生命週期

Fragment 依附 Activity 存在,Activity 的生命週期直接牽動 Fragment。相比 Activity,它多出幾個回調:

  • onAttach(Activity):Fragment 與 Activity 建立關聯時呼叫。
  • onCreateView(...):建立該 Fragment 的視圖。
  • onActivityCreated(Bundle):Activity 的 onCreate 執行完畢後呼叫。
  • onDestroyView():與 onCreateView 相對,視圖被移除時呼叫。
  • onDetach():與 onAttach 相對,關聯解除時呼叫。

注意:除 onCreateView 之外,其餘方法若被重寫,都必須呼叫父類的對應實作。

三、靜態使用:像普通 View 一樣宣告

最簡單的方式是把 Fragment 直接寫進 Activity 的佈局檔,步驟只有兩個:繼承 Fragment 並在 onCreateView 決定佈局;在 Activity 佈局中用 <fragment> 標籤宣告。

以下範例用兩個 Fragment 組成一個畫面:上方標題欄、下方內容區。

TitleFragment 的佈局:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="45dp"
    android:background="@drawable/title_bar" >

    <ImageButton
        android:id="@+id/id_title_left_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginLeft="3dp"
        android:background="@drawable/showleft_selector" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center"
        android:text="我不是微信"
        android:textColor="#fff"
        android:textSize="20sp" />
</RelativeLayout>
public class TitleFragment extends Fragment {

    private ImageButton mLeftMenu;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_title, container, false);
        mLeftMenu = (ImageButton) view.findViewById(R.id.id_title_left_btn);
        mLeftMenu.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getActivity(),
                        "i am an ImageButton in TitleFragment !",
                        Toast.LENGTH_SHORT).show();
            }
        });
        return view;
    }
}

ContentFragment 的佈局與實作:

<?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="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center"
        android:text="使用 Fragment 做主面板"
        android:textSize="20sp" />
</LinearLayout>
public class ContentFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_content, container, false);
    }
}

Activity 佈局中直接宣告兩個 Fragment:

<RelativeLayout 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" >

    <fragment
        android:id="@+id/id_fragment_title"
        android:name="com.zhy.zhy_fragments.TitleFragment"
        android:layout_width="fill_parent"
        android:layout_height="45dp" />

    <fragment
        android:layout_below="@id/id_fragment_title"
        android:id="@+id/id_fragment_content"
        android:name="com.zhy.zhy_fragments.ContentFragment"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />
</RelativeLayout>

把 Fragment 當普通 View 宣告,各自處理自己的事件,Activity 瞬間乾淨了幾倍——可讀性、複用性、可維護性一起提升。

四、動態使用:FragmentManager 與 FragmentTransaction

動態用法才是 Fragment 真正的價值所在。調整一下 Activity 佈局:頂部保留標題 Fragment,中間換成 FrameLayout 作為容器,底部放四個切換按鈕。

<RelativeLayout 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" >

    <fragment
        android:id="@+id/id_fragment_title"
        android:name="com.zhy.zhy_fragments.TitleFragment"
        android:layout_width="fill_parent"
        android:layout_height="45dp" />

    <include
        android:id="@+id/id_ly_bottombar"
        android:layout_width="fill_parent"
        android:layout_height="55dp"
        android:layout_alignParentBottom="true"
        layout="@layout/bottombar" />

    <FrameLayout
        android:id="@+id/id_content"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_above="@id/id_ly_bottombar"
        android:layout_below="@id/id_fragment_title" />
</RelativeLayout>
public class MainActivity extends Activity implements OnClickListener {

    private LinearLayout mTabWeixin;
    private LinearLayout mTabFriend;
    private ContentFragment mWeixin;
    private FriendFragment mFriend;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);

        mTabWeixin = (LinearLayout) findViewById(R.id.tab_bottom_weixin);
        mTabFriend = (LinearLayout) findViewById(R.id.tab_bottom_friend);
        mTabWeixin.setOnClickListener(this);
        mTabFriend.setOnClickListener(this);

        setDefaultFragment();
    }

    private void setDefaultFragment() {
        FragmentManager fm = getFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        mWeixin = new ContentFragment();
        transaction.replace(R.id.id_content, mWeixin);
        transaction.commit();
    }

    @Override
    public void onClick(View v) {
        FragmentManager fm = getFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        switch (v.getId()) {
            case R.id.tab_bottom_weixin:
                if (mWeixin == null) {
                    mWeixin = new ContentFragment();
                }
                transaction.replace(R.id.id_content, mWeixin);
                break;
            case R.id.tab_bottom_friend:
                if (mFriend == null) {
                    mFriend = new FriendFragment();
                }
                transaction.replace(R.id.id_content, mFriend);
                break;
        }
        transaction.commit();
    }
}

FriendFragment 的實作與 ContentFragment 幾乎一樣,只是載入不同佈局:

public class FriendFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_friend, container, false);
    }
}

補充一點:若專案要支援 Android 3.0 以下版本,需引入 support-v4 套件,Activity 改繼承 FragmentActivity,並透過 getSupportFragmentManager() 取得 FragmentManager。不過更建議把 Manifest 中 uses-sdk 的 minSdkVersion 與 targetSdkVersion 都設在 11 以上,就能直接用原生 API。

五、Fragment 家族的三個核心類別

  • android.app.Fragment:用來定義 Fragment 本身。
  • android.app.FragmentManager:在 Activity 中操作 Fragment。
  • android.app.FragmentTransaction:保證一系列 Fragment 操作的原子性。

取得 FragmentManager:getFragmentManager()(v4 套件中為 getSupportFragmentManager())。開啟事務:fm.beginTransaction()。

FragmentTransaction 常用方法

  • add():往 Activity 中加入一個 Fragment。
  • remove():移除 Fragment。若該 Fragment 沒有加入回退棧,實例會被銷毀。
  • replace():以另一個 Fragment 取代目前的,等同 remove() + add()。
  • hide():隱藏 Fragment,僅設為不可見,不銷毀。
  • show():顯示先前被隱藏的 Fragment。
  • detach():把 View 從 UI 樹移除,但 Fragment 狀態仍由 FragmentManager 維護。
  • attach():重建 View 並附加回 UI 顯示。
  • commit():提交事務。

常有人遇到 State loss 之類的狀態不一致錯誤,根因通常是:commit() 一定要在 Activity.onSaveInstanceState() 之前呼叫。

怎麼選?三個實務判斷

想保留使用者的操作內容(例如在 FragmentA 的 EditText 打了字,切到 B 再切回來還要看得到),用 hide() 與 show()。切記別每次都 new 新實例,記得做 null 判斷。

不打算保留操作狀態,用 remove() + add(),或直接 replace(),兩者效果相同。

remove 與 detach 的差別:不考慮回退棧的前提下,remove() 會銷毀整個 Fragment 實例,detach() 只銷毀視圖結構、實例仍在。若宿主 Activity 長期存在,又不需要保留操作狀態,優先選 detach() 更省資源。

把生命週期搞清楚了,那些曾經覺得 Fragment「問題一堆」的時刻,多半都能回溯到某個方法究竟銷毀了視圖、銷毀了實例,還是只是藏了起來。

由於篇幅關係,回退棧管理、Fragment 與 Activity 的互動最佳實踐、無佈局 Fragment 的用途、用 Fragment 建立對話框、以及與 ActionBar / MenuItem 整合,留待下一篇。

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