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

Fragment 完全解析(上):從誕生背景到動態使用

編輯:關於 Android 程式設計

曾經有段時間,好像聊什麼都能扯到 Fragment,做什麼都要先問一句「Fragment 能不能實現」。玩笑歸玩笑,Fragment 之所以被反覆提起,是因為它確實解決了一個真實存在的痛點。

本篇力圖把 Fragment 的來龍去脈講清楚:它為何誕生、生命週期如何運作、靜態與動態使用方式、以及 FragmentManager 與 FragmentTransaction 這家族常用 API 的底細。回退棧、與 Activity 互動、無版面配置 Fragment、建立對話框、與 ActionBar 整合等進階主題,留待下篇。

一、Fragment 為什麼會出現

Android 跑在各種尺寸相差十倍的設備上,從小手機到平板、電視。過去常見做法是手機版先做一套,再複製一份改版面去適配平板,維護成本極高。Fragment 的目標就是讓「一份程式碼同時適配多種尺寸」成為可能。

你可以把 Fragment 理解成 Activity 介面的一個組成部分,甚至整個介面都由多個 Fragment 拼成。更關鍵的是,Fragment 擁有自己的生命週期、能接收並處理使用者事件,也能在執行期動態新增、替換、移除。Activity 不必再被塞滿控件事件程式碼。

二、生命週期

Fragment 依附於 Activity 存在,因此 Activity 的生命週期直接牽動 Fragment。

相比 Activity,Fragment 多了幾個回呼:

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

特別注意:除了 onCreateView,其餘方法一旦重寫就必須呼叫父類的對應實作,否則容易出現各種莫名其妙的問題。

三、靜態使用 Fragment

最簡單的方式就是把 Fragment 當成普通控件,直接寫進 Activity 的版面配置檔。兩個步驟:繼承 Fragment 並在 onCreateView 決定版面;在 Activity 配置檔中宣告它。

TitleFragment 的配置:

<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 更單純,只負責把版面攤開:

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 處理,Activity 立刻乾淨清爽,可讀性、複用性與可維護性同步提升。

四、動態使用 Fragment

把 Activity 版面改成中間一個 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>
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();
}

補充一點:若使用 Android 3.0 以下版本,需引入 v4 套件包,Activity 繼承 FragmentActivity,並以 getSupportFragmentManager() 取得 FragmentManager。不過更建議直接把 Manifest 中 minSdkVersion 與 targetSdkVersion 調到 11 以上,省掉引入 v4 的麻煩。

五、Fragment 家族常用 API

三個核心類別:

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

取得 FragmentManager:getFragmentManager()(v4 版本為 getSupportFragmentManager())。主要操作都在 FragmentTransaction 上:

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

要留意的是經典的 IllegalStateException: State loss,成因通常是 commit 在 onSaveInstanceState() 之後才被呼叫。規則很簡單:commit 一定要在 Activity.onSaveInstance() 之前執行。

六、該用哪個方法?三個實務判斷

a. 想在 Fragment A 的 EditText 已輸入的內容在切到 B 再切回來後仍保留,用 hide/show。也就是說,凡是希望保留使用者操作狀態的面板,都適合 hide/show,記得搭配 null 判斷,不要每次都 new 新實例。

b. 不希望保留使用者操作,用 remove() 再 add(),或直接用 replace(),效果相同。

c. remove 與 detach 差別很細:不考慮回退棧時,remove 會銷毀整個 Fragment 實例,detach 只銷毀視圖結構。若 Activity 本身會長期存在,那麼在不需保留操作狀態時,優先選 detach。

把生命週期與這些 API 的行為摸清楚,你會發現過去 Fragment 帶來的種種怪問題,幾乎都能回溯到「沒搞懂哪個方法銷毀視圖、哪個銷毀實例、哪個只是隱藏」。下篇我們再談回退棧管理、Fragment 與 Activity 的互動最佳實踐、無視圖 Fragment 的妙用、用 Fragment 建立對話框,以及與 ActionBar、MenuItem 的整合。

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