編輯:關於 Android 程式設計
有面試經驗的人應該都體會過,Fragment 幾乎是每場 Android 面試的必考題。所以這次就把它單獨拉出來好好談一遍。
本文涵蓋:Fragment 的由來、定義、生命週期、靜態與動態使用方式、回退堆疊、Fragment 事務,以及一些特殊應用——沒有版面配置的 Fragment 有什麼用?如何與 Activity 互動?如何建立對話框?如何與 ActionBar 整合?
Android 跑在各種尺寸各異的裝置上,從小螢幕手機、超大螢幕平板到電視。面對這種落差,過去常見做法是把手機版 App 複製一份再改佈局來適配大屏,維護成本極高。
能不能一套 App 同時適配手機與平板?可以,答案就是 Fragment。它誕生的初衷正是解決這個問題。
你可以把 Fragment 視為 Activity 介面的一部分,甚至整個 Activity 的介面由多個 Fragment 組成。更棒的是 Fragment 有自己的生命週期、能接收並處理使用者事件,不必把一大堆控件初始化與事件程式碼全塞進同一個 Activity。而且 Fragment 可以動態新增、替換、移除。
Fragment 必須依附 Activity 存在,因此 Activity 的生命週期直接影響 Fragment。官方那張圖把兩者的關係講得很清楚:

相比 Activity,Fragment 多了幾個回呼:
· onAttach(Activity):Fragment 被關聯到 Activity。
· onCreateView(LayoutInflater, ViewGroup, Bundle):建立 Fragment 的檢視。
· onActivityCreated(Bundle):通知 Fragment 所屬 Activity 的 onCreate 已完成。
· onDestroyView():銷毀 onCreateView 建立的檢視。
· onDetach():解除與 Activity 的關聯。
關鍵區別在於:onCreateView() 建立的檢視會在 onDestroyView() 中被銷毀,而 Fragment 實例本身此時仍然存在。因此 Fragment 的檢視生命週期比實例生命週期短,這也是許多「資料莫名消失」問題的根源。
理解幾個重點:Fragment 是依賴 Activity 存在的;Fragment 有自己的生命週期,且檢視與實例的生命週期彼此獨立;Fragment 可以動態地從 Activity 中加入或移除。
最簡單的方式就是把 Fragment 當成普通控件寫進 XML。
標題欄的佈局 title_fragment.xml:
<?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" />
</RelativeLayout>
對應的 TitleFragment.java:
public class TitleFragment extends Fragment {
private ImageButton mButton;
@SuppressLint("NewApi")
@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;
}
}
可以注意到,每個 Fragment 都能獨立完成自己的控件初始化與事件處理,Activity 的負擔因此大幅減輕,程式碼可讀性也隨之提升。
內容區的佈局 content_fragment.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="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.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);
}
}
activity_main.xml 中,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"
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>
執行結果:

靜態宣告只能寫死結構,真正靈活的是動態操作。版面配置分三塊:頂部是靜態宣告的 TitleFragment,中間是可替換的內容區,底部用 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>
MainActivity 先載入佈局,再用 setDefaultFragment() 掛上預設的 ContentFragment,之後就能透過底部按鈕隨意切換:
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);
// 設置默認的 Fragment
setDefaultFragment();
}
@SuppressLint("NewApi")
private void setDefaultFragment() {
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
mWeiXinFragment = new ContentFragment();
transaction.replace(R.id.id_content, mWeiXinFragment);
transaction.commit();
}
@SuppressLint("NewApi")
@Override
public void onClick(View v) {
FragmentManager fm = getFragmentManager();
// 開啟 Fragment 事務
FragmentTransaction transaction = fm.beginTransaction();
switch (v.getId()) {
case R.id.weixin:
if (mWeiXinFragment == null) {
mWeiXinFragment = new ContentFragment();
}
// 使用當前 Fragment 的布局替代 id_content 的控件
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 的類別並設定佈局即可。
public class ContentFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_content, container, false);
}
}
<?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="weixin"
android:textSize="20sp" />
</LinearLayout>
public class FriendFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_friend, container, false);
}
}
執行後點擊下方不同按鈕,中間區域就會切換成對應的 Fragment,這也正是 Fragment 如此受歡迎的原因。

補充:若使用 Android 3.0 以下版本,需要引入 support v4 套件,並讓 Activity 繼承 FragmentActivity,再用 getSupportFragmentManager() 取得 FragmentManager;不過更建議把 Manifest 的 minSdkVersion 與 targetSdkVersion 調到 11 以上,就不用背 v4 的包袱。
Fragment 相關的三個核心類別:
· android.app.Fragment:定義 Fragment。
· android.app.FragmentManager:在 Activity 中操作 Fragment。
· android.app.FragmentTransaction:保證一系列 Fragment 操作的原子性。
取得 FragmentManager:getFragmentManager()(v4 套件中為 getSupportFragmentManager())。
主要操作都在 FragmentTransaction 上:
· add():往 Activity 中加入一個 Fragment。
· remove():移除 Fragment;若該 Fragment 沒有加入回退堆疊,實例會被銷毀。
· replace():以另一個 Fragment 取代當前,相當於 remove() 加 add()。
· hide():隱藏 Fragment,僅設為不可見,不會銷毀。
· show():顯示先前隱藏的 Fragment。
· detach():從 Activity 分離,會銷毀其檢視但不銷毀實例。
· attach():把分離的 Fragment 重新關聯回 Activity,重建檢視層級。
· commit():提交事務。
注意:常寫 Fragment 的人大概都遇過 IllegalStateException: Can not perform this action after onSaveInstanceState。原因很單純:commit() 必須在 Activity.onSaveInstanceState() 之前呼叫。
把這些方法用對,關鍵是搞清楚「哪個會銷毀檢視、哪個會銷毀實例、哪個只是隱藏」。
場景 A:Fragment A 的 EditText 填了資料,切到 B 之後還希望回到 A 時資料仍在——用 hide() 與 show()。也就是想保留使用者操作過的介面時用這組,同時別忘了做非 null 判斷,不要每次都 new 新實例。
場景 B:不希望保留使用者操作——用 remove() 再 add(),或直接用 replace(),效果相同。
場景 C:remove 與 detach 的細微差異在於:不考慮回退堆疊時,remove 會銷毀整個 Fragment 實例,detach 只銷毀檢視結構。如果當前 Activity 會一直存在,且不需要保留使用者操作,優先選 detach 更省資源。
把生命週期弄清楚之後,那些看似莫名其妙的 Fragment 問題大多就有了解釋。由於篇幅關係,回退堆疊管理、Fragment 與 Activity 的互動最佳實踐、無檢視 Fragment 的用途、用 Fragment 建立對話框、與 ActionBar 及 MenuItem 整合等內容,留待下一篇。
手把手帶你入門 Android 逆向分析
很多技術文章喜歡一上來鋪陳一大堆行業現狀、研究背景,寫得像畢業論文。這裡不來這套,先上兩張圖直觀感受一下成果。 第一張是把代碼注入到地圖 App 裡,啟動時彈出一個浮窗
Android 用 ExpandableListView 實作三層樹狀選單
在 Android 上要實作樹狀選單,通常會想到 ExpandableListView(也有高手自行繼承 ListView 或 LinearLayout 來做),但它一般
仿 vivo X6 閃充動畫:弧線與刻度的自定義 View 實作
自定義 View 練了一陣子之後,大致能寫出一些實用的小控件了。某天在家用手機,正好沒電在充電,看到那個充電動畫覺得挺有意思,就拆解了一下裡面的元素,心想這個我也能畫出來
Android 自定義 PopupMenu 樣式:顯示圖示與單選按鈕
PopupMenu 是 Android 中相當輕量的一顆元件。跟 PopupWindow 比起來,它的可客製空間有限,但勝在用法簡單直覺。本文要處理的兩個痛點是:如何強制