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

Android Fragment 完全指南:從生命週期到動態切換

編輯:關於 Android 程式設計

但凡面試過 Android 職位的人,大概都有過這樣的體驗:聊到界面架構時,Fragment 幾乎是繞不開的必考題。與其臨場硬背,不如趁早把它徹底吃透。本文就把 Fragment 從頭到尾梳理一遍。

一、Fragment 為何而生

Android 需要適配的手機、平板、電視在螢幕尺寸上差異巨大。過去很多團隊的做法是:先為手機做一套介面,再複製一份改改佈局去適配大屏,維護成本相當可觀。難道不能一套程式碼通吃嗎?Fragment 就是為了解決這個問題而出現的。

你可以把 Fragment 理解為 Activity 介面上的一段「可複用零件」,甚至整個 Activity 都由幾個 Fragment 拼裝而成。它有自己的生命週期,也能獨立接收並處理使用者事件,不必把一大堆控件初始化和點擊邏輯全塞進同一個 Activity。更關鍵的是,Fragment 支援在執行期動態地新增、替換與移除。

二、Fragment 的生命週期

Fragment 必須依附於 Activity 存在,因此 Activity 的生命週期會直接牽動 Fragment。相比 Activity,它多出了幾個專屬回呼:

onAttach(Activity)   // Fragment 與 Activity 建立關聯時呼叫
onCreateView(LayoutInflater, ViewGroup, Bundle)  // 建立 Fragment 的視圖
onActivityCreated(Bundle)  // Activity 的 onCreate() 執行完畢後呼叫
onDestroyView()      // 與 onCreateView 相對,視圖被銷毀時呼叫
onDetach()           // 與 onAttach 相對,關聯被解除時呼叫

需要留意的是:除了 onCreateView,其餘方法一旦重寫,都必須呼叫父類的對應實作,否則容易出現各種莫名其妙的崩潰。

三、靜態使用 Fragment

最直觀的用法是把 Fragment 當成一個普通控件,直接寫進 Activity 的佈局檔裡。兩個步驟即可:先繼承 Fragment 並在 onCreateView 中指定佈局,再在 Activity 佈局中以 <fragment> 標籤宣告。

下面用一個標題列 Fragment 搭配一個內容 Fragment 作為示範。標題列的佈局:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_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="fill_parent"
        android:layout_centerVertical="true"
        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"
        android:textStyle="bold" />
</RelativeLayout>

對應的 TitleFragment 在 onCreateView 裡完成控件初始化與事件綁定:

public class TitleFragment extends Fragment {
    private ImageButton mButton;

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

內容部分的佈局同樣獨立:

<?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"
        android:textStyle="bold" />
</LinearLayout>
public class ContentFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.content_fragment, container, false);
    }
}

MainActivity 本身反而變得非常清爽:

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
    }
}
<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"
    tools:context="com.example.staticfragment.MainActivity" >

    <fragment
        android:name="com.example.staticfragment.TitleFragment"
        android:id="@+id/title"
        android:layout_height="45dp"
        android:layout_width="match_parent"/>

    <fragment
        android:layout_below="@id/title"
        android:name="com.example.staticfragment.ContentFragment"
        android:id="@+id/content"
        android:layout_height="fill_parent"
        android:layout_width="fill_parent"/>
</RelativeLayout>

靜態方式的優點在於簡單直觀,缺點也很明顯:Fragment 一旦寫進佈局檔就無法在執行期更換,靈活性不足。

四、動態使用 Fragment

真正讓 Fragment 大放異彩的是動態切換。下面的例子頂部是一個靜態宣告的 TitleFragment,中間留出一塊 FrameLayout 容器供動態載入,底部則透過 include 引入的四個按鈕作為切換入口。

<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.example.dynamicfragment.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>

Activity 中透過 FragmentManager 開啟事務,用 replace 把容器內容換掉:

public class MainActivity extends ActionBarActivity implements OnClickListener {

    private ImageButton mTabWeixin;
    private ImageButton mTabFriend;
    private ContentFragment mWeiXinFragment;
    private FriendFragment mFriendFragment;

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

    public void initView() {
        mTabWeixin = (ImageButton) findViewById(R.id.weixin);
        mTabFriend = (ImageButton) findViewById(R.id.friend);
        mTabWeixin.setOnClickListener(this);
        mTabFriend.setOnClickListener(this);
        setDefaultFragment();
    }

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

    @Override
    public void onClick(View v) {
        FragmentManager fm = getFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        switch (v.getId()) {
            case R.id.weixin:
                if (mWeiXinFragment == null) {
                    mWeiXinFragment = new ContentFragment();
                }
                transaction.replace(R.id.id_content, mWeiXinFragment);
                break;
            case R.id.friend:
                if (mFriendFragment == null) {
                    mFriendFragment = new FriendFragment();
                }
                transaction.replace(R.id.id_content, mFriendFragment);
                break;
        }
        // transaction.addToBackStack();
        transaction.commit();
    }
}

被切換的 Fragment 本身,寫法與靜態宣告時完全一致——繼承 Fragment、在 onCreateView 中回傳佈局即可:

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

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() 取得管理器。當然,如果專案定位在較新版本,直接把 Manifest 中的 minSdkVersion 與 targetSdkVersion 調到 11 以上,就能省掉這層包裹。

五、接著可以往哪裡走

把上面的基礎打牢之後,還有幾個值得深入的方向:Fragment 回退棧的運作方式、FragmentTransaction 各個 API 的差異、無介面 Fragment(保留實例以在旋轉螢幕時-held 資料)、Fragment 與 Activity 之間的雙向溝通、用 DialogFragment 取代傳統 Dialog,以及 Fragment 與 ActionBar/Toolbar 的整合。這些主題都建立在本文的基礎之上,理解透了之後再往下鑽會順暢得多。

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