Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

深入淺析 Android Fragment(上篇):從誕生到動態操作

編輯:Android 開發實例

曾有一段時間,好像聊什麼都能扯到 Fragment,做什麼都要問一句「Fragment 能不能實現」——現在回想起來確實有點誇張,但它會紅,背後是有明確理由的。

Fragment 為什麼會出現

Android 3.0 為了讓介面能更好地呈現在平板上,引入了 Fragment(碎片)。它非常像 Activity,同樣能承載版面,但通常是嵌套在 Activity 裡使用。

想像一個常見場景:畫面左側一個 Fragment 放 ListView,每列顯示一本書的書名;右側另一個 Fragment 用 TextView 與 ImageView 呈現該書的詳細內容與封面。在手機上這兩個區塊上下堆疊,在平板上並排顯示——用 Activity 硬做的話,你得為兩種尺寸各寫一套,邏輯還得複製一遍。

Android 跑在手機、平板甚至電視等各種尺寸的裝置上。過去很多團隊的做法是先做手機版,再複製一份改版面去適配大屏。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):Activity 的 onCreate() 返回後呼叫。
  • onDestroyView():與 onCreateView() 相對,視圖被移除時呼叫。
  • onDetach():與 onAttach() 相對,關聯被解除時呼叫。

要特別注意:除了 onCreateView(),其餘方法一旦override就必須呼叫父類的實作,否則會出現各種莫名其妙的行為。

靜態使用:把 Fragment 當成一個控制項

這是最簡單的方式——直接在 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 瞬間乾淨清爽——可讀性、複用性、可維護性一次到位。

 

動態使用:FragmentTransaction 登場

靜態方式方便,但真正的價值在「動態」。要動態操作,得先在 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); } } 

 

Fragment 家族的三個關鍵類別

  • android.app.Fragment:定義 Fragment 本身。
  • android.app.FragmentManager:在 Activity 中操作 Fragment。
  • android.app.FragmentTransaction:保證一系列 Fragment 操作的原子性——理解「事務」這個詞,就懂它的意義了。

取得 manager:getFragmentManager()(v4 套件中為 getSupportFragmentManager())。

FragmentTransaction 的常用方法

FragmentTransaction transaction = fm.benginTransatcion();//開啟一個事務
  • add():往 Activity 中加入一個 Fragment。
  • remove():移除一個 Fragment。若該 Fragment 沒有被加入回退堆疊,其實例會被銷毀。
  • replace():以另一個 Fragment 取代目前的,本質上是 remove() 加 add() 的組合。
  • hide():把 Fragment 設為不可見,並不銷毀。
  • show():讓先前被 hide 的 Fragment 重新顯示。
  • detach():把 View 從 UI 上摘掉,與 remove() 不同,此時 Fragment 的狀態仍由 FragmentManager 維護。
  • attach():重建 View 並附加回 UI 顯示。
  • commit():提交事務。

frequent 使用 Fragment 的人大概都遇過 IllegalStateException: Can not perform this action after onSaveInstanceState 這類「狀態不一致」錯誤。原因很單純:commit() 必須在 Activity 的 onSaveInstanceState() 之前呼叫。

選哪個方法,取決於你想留下什麼

這些方法的差異不是細節,而是設計決策:

  • 想保留使用者操作過的內容(例如 EditText 裡打的字)→ 用 hide() 與 show()。切回來時畫面與資料都還在。當然,別忘了搭配 null 檢查,不要每次都 new 一個新實例。
  • 不想保留使用者操作 → 用 remove() 再 add(),或直接 replace(),效果相同。
  • remove 與 detach 的差別:不考慮回退堆疊時,remove() 會銷毀整個 Fragment 實例,detach() 只銷毀視圖結構、實例仍在。若宿主 Activity 會長期存在,又不需要保留使用者操作,detach() 通常是比較划算的選擇,因為重建 View 比重建整個 Fragment 便宜。

把生命週期與這些方法的關係弄清楚,你會發現過去那些「Fragment 一堆莫名其妙的問題」,幾乎都能回溯到同一個根源:沒搞懂它什麼時候被建立、什麼時候只是被藏起來。

下一篇接著談回退堆疊管理、Fragment 與 Activity 的互動、無版面 Fragment 的用途、DialogFragment 與 ActionBar 整合等進階題目,有興趣歡迎繼續追蹤。

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