編輯:Android 開發實例
曾有一段時間,好像聊什麼都能扯到 Fragment,做什麼都要問一句「Fragment 能不能實現」——現在回想起來確實有點誇張,但它會紅,背後是有明確理由的。
Android 3.0 為了讓介面能更好地呈現在平板上,引入了 Fragment(碎片)。它非常像 Activity,同樣能承載版面,但通常是嵌套在 Activity 裡使用。
想像一個常見場景:畫面左側一個 Fragment 放 ListView,每列顯示一本書的書名;右側另一個 Fragment 用 TextView 與 ImageView 呈現該書的詳細內容與封面。在手機上這兩個區塊上下堆疊,在平板上並排顯示——用 Activity 硬做的話,你得為兩種尺寸各寫一套,邏輯還得複製一遍。
Android 跑在手機、平板甚至電視等各種尺寸的裝置上。過去很多團隊的做法是先做手機版,再複製一份改版面去適配大屏。Fragment 就是為了終結這種複製貼上而出現的:你可以把 Fragment 當成 Activity 介面的一個組成部分,甚至整個 Activity 的畫面都由不同 Fragment 拼成。更棒的是,Fragment 擁有自己的生命週期,能接收並處理使用者事件,不必把一堆控制項的事件程式碼全塞進 Activity;而且它能被動態地加入、替換、移除。
Fragment 必須依附 Activity 存在,因此 Activity 的生命週期直接牽動 Fragment。官方這張圖把兩者的對應關係畫得很清楚:

相比 Activity,Fragment 多了幾個額外的回呼:
onCreate() 返回後呼叫。onCreateView() 相對,視圖被移除時呼叫。onAttach() 相對,關聯被解除時呼叫。要特別注意:除了 onCreateView(),其餘方法一旦override就必須呼叫父類的實作,否則會出現各種莫名其妙的行為。
這是最簡單的方式——直接在 Activity 的版面檔裡寫上 <fragment> 標籤。兩個步驟:繼承 Fragment 並在 onCreateView() 決定版面;然後在 Activity 版面中宣告它。
下面用兩個 Fragment 拼一個 Activity:一個當標題列,一個當內容區。
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" android:text /> </RelativeLayout>
TitleFragment:
package com.zhy.zhy_fragments; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.Toast; 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" android:text /> </LinearLayout>
ContentFragment:
package com.zhy.zhy_fragments; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class ContentFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_content, container, false); } }
MainActivity:
package com.zhy.zhy_fragments; import android.app.Activity; import android.os.Bundle; import android.view.Window; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_main); } }
Activity 的版面:
<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 一樣被宣告在版面裡,各自的控制項事件由各自的 Fragment 處理,Activity 瞬間乾淨清爽——可讀性、複用性、可維護性一次到位。

靜態方式方便,但真正的價值在「動態」。要動態操作,得先在 Activity 版面中留一個容器(這裡用 FrameLayout),作為 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" /> <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:
package com.zhy.zhy_fragments; import android.app.Activity; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.LinearLayout; 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); // 設置默認的Fragment 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(); // 開啟Fragment事務 FragmentTransaction transaction = fm.beginTransaction(); switch (v.getId()) { case R.id.tab_bottom_weixin: if (mWeixin == null) { mWeixin = new ContentFragment(); } // 使用當前Fragment的布局替代id_content的控件 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.addToBackStack(); // 事務提交 transaction.commit(); } }
這裡透過 FragmentManager 動態載入 Fragment,用的是 replace()。
註:若需支援 Android 3.0 以下版本,要引入 v4 套件並讓 Activity 繼承 FragmentActivity,再透過 getSupportFragmentManager() 取得 manager。不過更建議直接把 Manifest 的 minSdkVersion 與 targetSdkVersion 設在 11 以上,省掉 v4 這層負擔。
另外兩個 Fragment 子類也順手附上,FriendFragment 與 ContentFragment 幾乎一樣:
package com.zhy.zhy_fragments; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; 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.app.Fragment:定義 Fragment 本身。android.app.FragmentManager:在 Activity 中操作 Fragment。android.app.FragmentTransaction:保證一系列 Fragment 操作的原子性——理解「事務」這個詞,就懂它的意義了。取得 manager:getFragmentManager()(v4 套件中為 getSupportFragmentManager())。
FragmentTransaction transaction = fm.benginTransatcion();//開啟一個事務
remove() 加 add() 的組合。remove() 不同,此時 Fragment 的狀態仍由 FragmentManager 維護。 frequent 使用 Fragment 的人大概都遇過 IllegalStateException: Can not perform this action after onSaveInstanceState 這類「狀態不一致」錯誤。原因很單純:commit() 必須在 Activity 的 onSaveInstanceState() 之前呼叫。
這些方法的差異不是細節,而是設計決策:
hide() 與 show()。切回來時畫面與資料都還在。當然,別忘了搭配 null 檢查,不要每次都 new 一個新實例。remove() 再 add(),或直接 replace(),效果相同。remove() 會銷毀整個 Fragment 實例,detach() 只銷毀視圖結構、實例仍在。若宿主 Activity 會長期存在,又不需要保留使用者操作,detach() 通常是比較划算的選擇,因為重建 View 比重建整個 Fragment 便宜。把生命週期與這些方法的關係弄清楚,你會發現過去那些「Fragment 一堆莫名其妙的問題」,幾乎都能回溯到同一個根源:沒搞懂它什麼時候被建立、什麼時候只是被藏起來。
下一篇接著談回退堆疊管理、Fragment 與 Activity 的互動、無版面 Fragment 的用途、DialogFragment 與 ActionBar 整合等進階題目,有興趣歡迎繼續追蹤。
Android 圖片處理實例大全:圓角、濾鏡到銳化一次學會
行動應用裡的視覺呈現,很大一部分靠圖片處理撐起來:頭像要圓角、照片要濾鏡、細節要銳化。Android 的 Bitmap 搭配 Canvas、Paint 與像素陣列操作,就
Android 教學:依系列圖片繪製動畫的三種做法
本文要說明如何依據一系列圖片來繪製動畫。根據素材的不同,主要可以分成三種做法,以下逐一介紹。一、使用系統提供的 Animation 類這種方式最簡單,用自帶的方法即可。其
Android 加載 Spinner:不確定進度的視覺提示
什麼是 Spinner?在 Android 中,進度條可分為確定性進度條與不確定型進度條。當任務完成時間未知時, Spinner 常用來提示使用者系統仍在處理中。宣告與取
Android 系統在靜音模式下關閉相機拍照聲音的實作方法
為了防止偷拍,業界有不成文的規定:手機廠商在製作相機時,點擊拍照與錄影鍵必須有提示音。因此 Google 也將播放拍照聲音的函式放進了 cameraService 中,寫