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

深入解析 Android Fragment(上篇)

編輯:關於 Android 程式設計

自從 Fragment 問世,曾有段時間感覺大家聊什麼都能扯上它,做什麼都要問一句「Fragment 能不能實現」。為了讓介面在平板上更好地呈現,Android 從 3.0 版本引入了 Fragment(碎片)機制,它非常類似於 Activity,同樣可以承載版面配置,通常嵌套在 Activity 中使用。

想像這樣一個情境:有兩個 Fragment,Fragment 1 裡有一個 ListView,每一行顯示一本書的標題;Fragment 2 則包含 TextView 與 ImageView,用來呈現該書的詳細內容與封面圖片。

本篇將為大家說明 Fragment 的由來、它是什麼、生命週期、如何靜態與動態地使用它,以及回退堆疊、Fragment 事務,還有一些特殊用途,例如無版面 Fragment 有何用處、如何與 Activity 互動、如何建立對話框、如何與 ActionBar 整合等等。

1、Fragment 的產生與介紹

Android 運行在五花八門的裝置上,有小螢幕的手機,也有超大螢幕的平板甚至電視。針對螢幕尺寸的差異,過去很多團隊都是先為手機開發一套 App,再複製一份修改版面去適配平板。難道無法做到一個 App 同時適應手機與平板嗎?當然可以,而 Fragment 的出現正是為了解決這個痛點。你可以把 Fragment 當成 Activity 介面的一個組成部分,甚至整個 Activity 的介面都由不同的 Fragment 拼裝而成;更棒的是,Fragment 擁有自己的生命週期,能接收並處理使用者事件,如此一來就不必把一堆控件事件處理程式碼全塞進 Activity 裡。更為關鍵的是,你能動態地新增、替換與移除某個 Fragment。

2、Fragment 的生命週期

Fragment 必須依附 Activity 而存在,因此 Activity 的生命週期會直接影響 Fragment。官方這張圖很好地說明了兩者的關係:

可以看到 Fragment 比 Activity 多了幾個額外的生命週期回調方法:

onAttach(Activity)——當 Fragment 與 Activity 發生關聯時呼叫。

onCreateView(LayoutInflater, ViewGroup, Bundle)——建立該 Fragment 的檢視。

onActivityCreated(Bundle)——當 Activity 的 onCreate 方法返回時呼叫。

onDestoryView()——與 onCreateView 相對應,當 Fragment 的檢視被移除時呼叫。

onDetach()——與 onAttach 相對應,當 Fragment 與 Activity 的關聯被取消時呼叫。

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

3、靜態地使用 Fragment

終於來到使用環節了。這是最簡單的一種方式:把 Fragment 當成普通控件,直接寫在 Activity 的佈局檔中。步驟是:先繼承 Fragment 並重寫 onCreateView 決定它的版面,再在 Activity 佈局中像普通 View 一樣聲明它。下面用兩個 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> 

java

 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 一樣聲明在 Activity 佈局中,再把各控件的事件處理交給各自的 Fragment,Activity 瞬間就清爽了起來?程式碼的可讀性、複用性與可維護性都跟著提升。下面看效果圖:

4、動態地使用 Fragment

上面演示了最簡單的用法,接著來看如何動態地新增、更新與刪除 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>

底部四個按鈕的佈局這裡就不貼了,看效果圖即可明白。

下面是主 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 方法,下一節會詳細介紹 FragmentManager 的常用 API。

註:若使用 Android 3.0 以下版本,需要引入 v4 套件包,讓 Activity 繼承 FragmentActivity,再透過 getSupportFragmentManager 取得 FragmentManager。不過還是建議把 Manifest 中 uses-sdk 的 minSdkVersion 與 targetSdkVersion 都設為 11 以上,如此就不必引入 v4 包了。

程式碼中還有兩個 Fragment 子類,ContentFragment 前面已見過,FriendFragment 也類似:

 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); } } 

效果圖:

可以看到效果實現得很好。為了讓程式碼保持簡潔,這裡就不加入按鈕點擊的視覺變化了,重點放在功能講解上。

5、Fragment 家族常用的 API

Fragment 常用的三個類:

android.app.Fragment——主要用於定義 Fragment。

android.app.FragmentManager——主要用於在 Activity 中操作 Fragment。

android.app.FragmentTransaction——保證一系列 Fragment 操作的原子性,理解「事務」這個詞就一定能明白。

a、取得 FragmentManager 的方式: getFragmentManager()(v4 中則是 getSupportFragmentManager)。

b、主要操作都是 FragmentTransaction 的方法

FragmentTransaction transaction = fm.beginTransaction(); 開啟一個事務。

transaction.add()——往 Activity 中加入一個 Fragment。

transaction.remove()——從 Activity 中移除一個 Fragment,若被移除的 Fragment 沒有加入回退堆疊,其實例將會被銷毀。

transaction.replace()——用另一個 Fragment 替換當前的,實際上就是 remove() 加 add() 的組合。

transaction.hide()——隱藏當前 Fragment,僅設為不可見,並不會銷毀。

transaction.show()——顯示之前隱藏的 Fragment。

detach()——會把 view 從 UI 中移除,和 remove() 不同,此時 Fragment 的狀態仍由 FragmentManager 維護。

attach()——重建 view 檢視,附加到 UI 上並顯示。

transaction.commit()——提交一個事務。

注意:常寫 Fragment 的朋友可能經常遇到「State loss」這樣的錯誤,主要是因為 commit 方法一定要在 Activity.onSaveInstance() 之前呼叫。

上述基本涵蓋了操作 Fragment 的所有方式,在一個事務從開啟到提交之間可以進行多個新增、移除、替換等操作。值得留意的是:如果你愛用 Fragment,一定要清楚哪個方法會銷毀檢視、哪個會銷毀實例、哪個僅僅只是隱藏,這樣才能用得更好。

a、比如我在 FragmentA 的 EditText 填了一些資料,切換到 FragmentB 後若希望回到 A 還能看到資料,適合你的就是 hide 和 show;也就是說,想保留使用者操作的畫面時,用 hide 和 show 即可,當然別忘了做個非 null 判斷,不要一個勁地 new 實例。

b、再比如我不希望保留使用者操作,可以用 remove() 再 add();或者直接用 replace(),效果與 remove、add 相同。

c、remove 和 detach 有一點細微差別:在不考慮回退堆疊的情況下,remove 會銷毀整個 Fragment 實例,而 detach 只銷毀其檢視結構,實例並不會被銷毀。若當前 Activity 一直存在,那麼在不希望保留使用者操作時,可以優先使用 detach。

介紹完 Fragment 的常用方法,相信大家已經清楚 Fragment 的由來與用法,再對照 API 說明,也能明白曾經為何会觉得 Fragment 問題層出不窮——歸根結底還是因為沒弄清楚它的生命週期。敬請期待下篇《深入淺析 Android Fragment(下篇)》,本文若有寫得不到位之處,歡迎留言指正,謝謝!

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