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

Android Fragment 完全指南:建立、生命週期、管理與互動實作

編輯:Android 開發實例

前言

本文將帶你完整認識 Android 中的 Fragment,關鍵環節都會附上可運行的示範程式碼,最後並提供源碼下載。

本文涵蓋:

  1. 什麼是 Fragment
  2. 如何建立一個 Fragment
  3. Fragment 的生命週期
  4. 如何管理 Fragment
  5. Fragment 之間如何互動
  6. Fragment 的向下相容

 

什麼是 Fragment

Fragment,中文譯為「碎片」,是 Android 3.0 之後新增的特性,主要是為了在大螢幕裝置(如平板)上支援更靈活的 UI 設計。隨著裝置螢幕日益增大,善用 Fragment 能更從容地管理視圖層次的變化。與 Activity 類似,我們可以建立 Fragment 來承載 View、進行布局,但 Fragment 必須嵌入 Activity 之中,無法單獨存在;而且一個 Activity 可以嵌入多個 Fragment,同一個 Fragment 也能被多個 Activity 重複使用。

下圖引自官方文件,清楚說明了 Activity 與 Fragment 的關係與優勢。在平板上,由於螢幕大、可顯示的內容多,若還像手機那樣靠 Activity 跳轉來切換 UI,未免太浪費螢幕空間。如左圖所示,透過 Fragment 布局,可讓一個 Activity 左右各嵌一個 Fragment,於是操作左側 Fragment 就能即時影響右側 Fragment 的顯示,典型場景如新聞閱讀、系統設定等。若一個應用採用 Activity + Fragment 的組合布局,便能輕鬆在手機與平板間互相移植,大部分程式碼都能重用,而且 Fragment 無需在 AndroidManifest.xml 清單檔中註冊。

如何建立一個 Fragment

認識了 Fragment,接著談談怎麼用。使用 Fragment 必須繼承 Fragment 類或其子類,並重寫 onCreateView() 方法——這個方法用來指定 Fragment 初次載入時顯示的 View。其簽名如下:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)

  • inflater:當前布局的填充者,可用 inflater.inflate() 填充一個布局檔。
  • container:包裹當前 Fragment 的容器,通常是一個布局控件。
  • savedInstanceState:當前實例的狀態,一般用不上。

onCreateView() 需回傳一個 View 供 Fragment 顯示,這裡以 inflater.inflate() 動態膨脹出一個 View 作為回傳值,inflate() 的簽名如下:

public View inflate(int resource, ViewGroup root, boolean attachToRoot)

  • resource:要動態膨脹的布局資源 ID。
  • root:膨脹出的 View 的上層布局物件,一般傳入 onCreateView 的 container 參數即可。
  • attachToRoot:指定展開的布局是否依附到 root 這個 ViewGroup,一般傳入 false 即可。

inflate() 的 resource 就是一個普通的布局資源,別無特殊。而在布局檔中使用 Fragment,則需用 <fragment/> 標籤,多數屬性與一般 UI 控件相同,但有兩個屬性要特別留意:

  • android:name:該 Fragment 的實作類。
  • android:layout_weight:當前 Fragment 在 Activity 中的權重,數值越大,佔的權重越高。

以下用一個範例,演示 Fragment 在 Activity 中的應用,在單一 Activity 裡加入兩個 Fragment。

activity_fragment.xml:

 

  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" 
  3.     android:layout_width="match_parent" 
  4.     android:layout_height="match_parent" 
  5.     android:orientation="horizontal" > 
  6.  
  7.     <fragment 
  8.         android:id="@+id/fragment1" 
  9.         android:name="com.example.fragmentSimple.Fragment1" 
  10.         android:layout_width="0px" 
  11.         android:layout_height="match_parent" 
  12.         android:layout_weight="2" /> 
  13.  
  14.     <fragment 
  15.         android:id="@+id/fragment2" 
  16.         android:name="com.example.fragmentSimple.Fragment2" 
  17.         android:layout_width="0px" 
  18.         android:layout_height="match_parent" 
  19.         android:layout_weight="1" /> 
  20.  
  21. </LinearLayout> 

Fragment1:

  1. package com.example.fragmentSimple; 
  2.  
  3. import com.example.fragmentdemo.R; 
  4. import android.app.Fragment; 
  5. import android.os.Bundle; 
  6. import android.view.LayoutInflater; 
  7. import android.view.View; 
  8. import android.view.ViewGroup; 
  9.  
  10. public class Fragment1 extends Fragment { 
  11.  
  12.     @Override 
  13.     public View onCreateView(LayoutInflater inflater, ViewGroup container, 
  14.             Bundle savedInstanceState) { 
  15.         // 填充一個布局View到ViewGrope中 
  16.         return inflater.inflate(R.layout.fragment1, container, false);        
  17.     } 
  18. }

Fragment2:

 

  1. package com.example.fragmentSimple; 
  2.  
  3. import com.example.fragmentdemo.R; 
  4.  
  5. import android.os.Bundle; 
  6. import android.app.Fragment; 
  7. import android.view.LayoutInflater; 
  8. import android.view.View; 
  9. import android.view.ViewGroup; 
  10.  
  11. public class Fragment2 extends Fragment { 
  12.  
  13.     @Override 
  14.     public View onCreateView(LayoutInflater inflater, ViewGroup container, 
  15.             Bundle savedInstanceState) { 
  16.         return inflater.inflate(R.layout.fragment2, container, false);        
  17.     } 
  18. }

啟動後的顯示效果:

 

Fragment 的生命週期

Fragment 擁有自己獨立的生命週期,但它依附於 Activity,因此其生命週期直接受 Activity 牽動。下圖很直觀地描繪了 Fragment 的生命週期:

從圖中不難看出,Fragment 的生命週期大體與 Activity 相仿,但有兩個方法值得留意:onAttach()(附加)與 onDetach()(剝離)。從這兩者的位置可知,Fragment 在建立時會先附加到 Activity,之後才從 onCreateView() 載入 View——這一點相當重要。而在生命週期終點,順序則相反:先銷毀 onDestroy(),再回呼 onDetach() 從 Activity 剝離該 Fragment。

如何管理一個 Fragment

在程式碼中管理 Fragment 相當簡單,關鍵在於一個 FragmentTransaction 物件。它透過 getFragmentManager().beginTransaction() 取得,會開啟一個事務,用來操作某個 ViewGroup 中的 Fragment。

FragmentTransaction 的常用方法:

  • add():新增一個 Fragment,具多重重載。
  • replace():替換一個 Fragment,具多重重載。
  • remove():移除指定的 Fragment。
  • addToBackStack():在事務中加入一個堆疊,供回退使用。
  • commit():提交事務。

其中 add、replace、remove 都是常見操作,無須多作解釋。但 addToBackStack() 就得額外說明。正常情況下,應用中的 Activity 由一個任務堆疊管理,我們在不同 Activity 間跳轉時,按返回鍵总能回到上一個 Activity。而 Fragment 是嵌套在 Activity 裡的,預設無法進入 Activity 的任務堆疊,因此按返回時只會回到上一個 Activity,不會理會 Fragment 的操作(add、replace、remove)。而 addToBackStack() 能把當前事務加入另一個由 Fragment 所屬 Activity 管理的堆疊,這個堆疊的每一筆都是 Fragment 的一次事務;有了它,便能透過返回鍵反向回滾 Fragment 的事務。這一點相當關鍵,因為 Fragment 無需在清單檔中配置,如今有些應用正是靠 Fragment 來完成布局跳轉。

以下用一個範例,演示動態操作 Fragment:實作一個分欄效果,點擊左側項目會動態改變右側內容。

布局檔 activity_fragmenttab.xml:

  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" 
  3.     android:layout_width="match_parent" 
  4.     android:layout_height="match_parent" 
  5.     android:orientation="horizontal" > 
  6.  
  7.     <LinearLayout 
  8.         android:layout_width="wrap_content" 
  9.         android:layout_height="match_parent" 
  10.         android:orientation="vertical" > 
  11.  
  12.         <TextView 
  13.             android:id="@+id/tabfgt1" 
  14.             android:layout_width="wrap_content" 
  15.             android:layout_height="wrap_content" 
  16.             android:text="fragment1" /> 
  17.  
  18.         <TextView 
  19.             android:id="@+id/tabfgt2" 
  20.             android:layout_width="wrap_content" 
  21.             android:layout_height="wrap_content" 
  22.             android:text="fragment2" /> 
  23.  
  24.         <TextView 
  25.             android:id="@+id/tabfgt3" 
  26.             android:layout_width="wrap_content" 
  27.             android:layout_height="wrap_content" 
  28.             android:text="fragment3" /> 
  29.     </LinearLayout> 
  30.  
  31.     <LinearLayout 
  32.         android:id="@+id/content" 
  33.         android:layout_width="match_parent" 
  34.         android:layout_height="match_parent" 
  35.         android:orientation="vertical" > 
  36.     </LinearLayout> 
  37.  
  38. </LinearLayout> 

FragmentTabActivity.java:

 

  1. package com.example.fragmentTab; 
  2.  
  3. import com.example.fragmentSimple.Fragment1; 
  4. import com.example.fragmentSimple.Fragment2; 
  5. import com.example.fragmentTurn.Fragment3; 
  6. import com.example.fragmentdemo.R; 
  7.  
  8. import android.app.Activity; 
  9. import android.app.FragmentManager; 
  10. import android.app.FragmentTransaction; 
  11. import android.graphics.Color; 
  12. import android.os.Bundle; 
  13. import android.view.View; 
  14. import android.widget.TextView; 
  15.  
  16. public class FragmentTabActivity extends Activity { 
  17.     private TextView tabfgt1, tabfgt2, tabfgt3; 
  18.  
  19.     @Override 
  20.     protected void onCreate(Bundle savedInstanceState) { 
  21.         // TODO Auto-generated method stub 
  22.         super.onCreate(savedInstanceState); 
  23.         setContentView(R.layout.activity_fragmenttab); 
  24.  
  25.         tabfgt1 = (TextView) findViewById(R.id.tabfgt1); 
  26.         tabfgt2 = (TextView) findViewById(R.id.tabfgt2); 
  27.         tabfgt3 = (TextView) findViewById(R.id.tabfgt3); 
  28.  
  29.         tabfgt1.setOnClickListener(click); 
  30.         tabfgt2.setOnClickListener(click); 
  31.         tabfgt3.setOnClickListener(click); 
  32.  
  33.     } 
  34.  
  35.     private View.OnClickListener click = new View.OnClickListener() { 
  36.  
  37.         @Override 
  38.         public void onClick(View v) { 
  39.             tabfgt1.setBackgroundColor(Color.GRAY); 
  40.             tabfgt2.setBackgroundColor(Color.GRAY); 
  41.             tabfgt3.setBackgroundColor(Color.GRAY); 
  42.             // 獲取FragmentManager對象 
  43.             FragmentManager fm = getFragmentManager(); 
  44.             // 開啟事務 
  45.             FragmentTransaction ft = fm.beginTransaction(); 
  46.             switch (v.getId()) { 
  47.                 case R.id.tabfgt1: 
  48.                     tabfgt1.setBackgroundColor(Color.GREEN); 
  49.                     // 替換R.id.content中的Fragment 
  50.                     ft.replace(R.id.content, new Fragment1()); 
  51.                 break; 
  52.                 case R.id.tabfgt2: 
  53.                     tabfgt2.setBackgroundColor(Color.YELLOW); 
  54.                     ft.replace(R.id.content, new Fragment2()); 
  55.                 break; 
  56.                 case R.id.tabfgt3: 
  57.                     tabfgt3.setBackgroundColor(Color.RED); 
  58.                     ft.replace(R.id.content, new Fragment3()); 
  59.                 break; 
  60.                 default: 
  61.                 break; 
  62.             } 
  63.             // 提交事務 
  64.             ft.commit(); 
  65.         } 
  66.     }; 
  67. }

效果展示:

Fragment 之間如何互動

既然 Fragment 嵌套在 Activity 中,而 Fragment 載入的布局檔裡又能再放額外布局,於是就冒出一個新問題:該如何操作分屬不同 Fragment 的控件呢?回想一下,在 Activity 中操作控件是靠 findViewById(int) 透過 ID 找到它;而 Fragment 最終在 onCreateActivity() 階段會把膨脹的 View 掛載到 Activity 上,因此可以直接在 Activity 中用 findViewById() 找到控件進而操作,這與直接操作 Activity 的方式一致。但若要在某個 Fragment 中操作另一個 Fragment 的控件,就得借助 Fragment.getActivity() 取得當前 Fragment 所依附的 Activity 物件,拿到它之後,要取其中的控件自然不成問題。

以下用一個範例演示 Fragment 間的互動:Activity 中有三個 Fragment,從其中一個 Fragment 的 Button 點擊時,去修改其他 Fragment 的值。

布局 activity_fragmentturn.xml

  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" 
  3.     android:layout_width="match_parent" 
  4.     android:layout_height="match_parent" 
  5.     android:orientation="horizontal" > 
  6.  
  7.     <fragment 
  8.         android:id="@+id/fragment1" 
  9.         android:name="com.example.fragmentSimple.Fragment1" 
  10.         android:layout_width="0px" 
  11.         android:layout_height="match_parent" 
  12.         android:layout_weight="1" /> 
  13.     <!-- 加載了兩個Fragment1 --> 
  14.      <fragment 
  15.         android:id="@+id/fragment2" 
  16.         android:name="com.example.fragmentSimple.Fragment1" 
  17.         android:layout_width="0px" 
  18.         android:layout_height="match_parent" 
  19.         android:layout_weight="1" /> 
  20.     <fragment 
  21.         android:id="@+id/fragment3" 
  22.         android:name="com.example.fragmentTurn.Fragment3" 
  23.         android:layout_width="0px" 
  24.         android:layout_height="match_parent" 
  25.         android:layout_weight="1" /> 
  26.  
  27. </LinearLayout> 

帶 Button 的 Fragment:

  1. package com.example.fragmentTurn; 
  2.  
  3. import com.example.fragmentdemo.R; 
  4.  
  5. import android.app.Fragment; 
  6. import android.os.Bundle; 
  7. import android.view.LayoutInflater; 
  8. import android.view.View; 
  9. import android.view.ViewGroup; 
  10. import android.widget.Button; 
  11. import android.widget.TextView; 
  12. import android.widget.Toast; 
  13. public class Fragment3 extends Fragment { 
  14.  
  15.      
  16.     @Override 
  17.     public View onCreateView(LayoutInflater inflater, ViewGroup container, 
  18.             Bundle savedInstanceState) { 
  19.         // TODO Auto-generated method stub 
  20.         return inflater.inflate(R.layout.fragment3, container, false);        
  21.     } 
  22.     @Override 
  23.     public void onStart() { 
  24.         super.onStart(); 
  25.         // 方法2: 在Fragment中獲取操作其他Fragment的控件 
  26. //        Button btnGetText=(Button)getActivity().findViewById(R.id.btnGetText); 
  27. //        btnGetText.setOnClickListener(new View.OnClickListener() { 
  28. //             
  29. //            @Override 
  30. //            public void onClick(View v) { 
  31. //                TextView tv=(TextView)getActivity().findViewById(R.id.tvFragment1); 
  32. //                Toast.makeText(getActivity(), tv.getText().toString()   ,Toast.LENGTH_SHORT).show();                
  33. //            } 
  34. //        }); 
  35.     } 
  36. }

FragmentTurnActivity.java:

 

  1. package com.example.fragmentTurn; 
  2.  
  3.  
  4. import com.example.fragmentdemo.R; 
  5.  
  6. import android.app.Activity; 
  7. import android.os.Bundle; 
  8. import android.view.View; 
  9. import android.widget.Button; 
  10. import android.widget.TextView; 
  11. import android.widget.Toast; 
  12.  
  13. public class FragmentTurnActivity extends Activity { 
  14.     @Override 
  15.     protected void onCreate(Bundle savedInstanceState) { 
  16.         // TODO Auto-generated method stub 
  17.         super.onCreate(savedInstanceState); 
  18.         setContentView(R.layout.activity_fragmentturn); 
  19.         // 方法1:在Activity中操作旗下Fragment中的控件 
  20.         Button btn=(Button)findViewById(R.id.btnGetText); 
  21.         btn.setOnClickListener(new View.OnClickListener() { 
  22.              
  23.             @Override 
  24.             public void onClick(View v) {                 
  25.                 TextView tv=(TextView)findViewById(R.id.tvFragment1); 
  26.                 tv.setText("動態修改"); 
  27.                 Toast.makeText(FragmentTurnActivity.this,tv.getText().toString() ,Toast.LENGTH_SHORT    ).show(); 
  28.             } 
  29.         }); 
  30.     } 
  31. }

效果展示:

 

 上面的例子還藏著一個陷阱:無論在 Activity 中用 findViewById(),還是在 Fragment 中用 getActivity().findViewById(),雖然都能取到控件,但有個例外——當 Activity 中同時放了兩個一模一樣的 Fragment 時,僅靠上述方法只能透過 ID 取到第一個 Fragment 裡的控件。原因在於,布局檔中定義的控件即便 ID 重複,Android SDK 維護的 R.java 也只會宣告一次,也就是說,想在 Activity 中區分同一 Fragment 類別的兩個實例裡的控件,是辦不到的。

那只好換個思路。我的解法是:在 Fragment 中宣告一個 View 變數,於 onCreateView 中把膨脹的 View 不直接回傳,而是先引用到這個變數上;之後在需要的任何地方,用 getFragmentManager().findFragmentById(int) 透過 Fragment 的 ID 找到該物件,再取出其中的 View,用 View.findViewById(int) 定位到對應 ID 的控件進而操作(這裡就不另附範例了)。這方法雖能解決問題,但一般並不推薦,因為大多數場景根本没必要在一個 Activity 裡放兩個相同的 Fragment。

 

Fragment 的向下相容

前面提過,Fragment 是 Android 3.0 之後才有的特性。而對於低版本的裝置,Google 也沒放著不管。細心的朋友應該會發現,引入 Fragment 的套件時有兩個選項:android.app.Fragment 與 android.support.v4.app.Fragment,其中後者正是為了相容低版本而準備的,直接引用它即可。

一般來說,若考慮向下相容,建議直接引用 android.support.v4.app.Fragment 進行開發,就不必再為相容性煩惱。

 

源碼下載

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