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

Android Fragment 完全入門:靜態嵌入、動態替換、返回堆疊與生命週期

編輯:關於 Android 程式設計

Fragment(碎片)是可以嵌入 Activity 的 UI 片段。它把「畫面的一部分」拆成可重複組合的單元,在手機與平板共用版面、或需要 Tab 式切換時特別好用。本文從最簡單的用法一路談到生命週期。

一、最簡單的用法

先準備兩個版面:

 <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="Button" /> </LinearLayout> //left_fragment.xml 
 <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#00ff00" android:orientation="vertical" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:textSize="20sp" android:text="This is right fragment" /> </LinearLayout> //right_fragment.xml 

自訂的 Fragment 都必須繼承 Fragment 類別,並在 onCreateView() 中 inflate 自己的版面:

 public class LeftFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.left_fragment, container, false); return view; } } public class RightFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.right_fragment, container, false); return view; } } 

最後在主版面中用 <fragment> 標籤把它們放進來:

 <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <fragment android:id="@+id/left_fragment" android:name="com.example.fragmenttest.LeftFragment" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" /> <fragment android:id="@+id/right_fragment" android:name="com.example.fragmenttest.RightFragment" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" /> </LinearLayout> 

這種寫法叫靜態嵌入,版面一經 inflate 就無法在執行期替換,適合固定分割的雙欄式設計。

二、動態添加碎片

 @Override public void onClick(View v) { switch (v.getId()) { case R.id.button: AnotherRightFragment fragment = new AnotherRightFragment(); FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction transaction = fragmentManager. beginTransaction(); transaction.replace(R.id.right_layout, fragment); transaction.commit(); break; default: break; } } 

流程可拆成五步:

1、建立待加入的 Fragment 實例;
2、取得 FragmentManager(Activity 中直接呼叫 getFragmentManager());
3、呼叫 beginTransaction() 開啟一個事務;
4、用 replace() 把容器 id 與 Fragment 傳入,完成替換;
5、呼叫 commit() 提交。

三、用返回鍵回到上一個碎片

預設情況下,動態加入碎片後按 Back 鍵會直接結束程式。若希望返回鍵回到上一個碎片,只要在提交前呼叫 addToBackStack(null):

 public class MainActivity extends Activity implements OnClickListener { ...... @Override public void onClick(View v) { switch (v.getId()) { case R.id.button: AnotherRightFragment fragment = new AnotherRightFragment(); FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction transaction = fragmentManager. beginTransaction(); transaction.replace(R.id.right_layout, fragment); transaction.addToBackStack(null); transaction.commit(); break; default: break; } } } 

四、碎片與 Activity 的雙向溝通

Activity 想取得版面中的 Fragment 實例,FragmentManager 提供了類似 findViewById 的方法:

 RightFragment rightFragment = (RightFragment) getFragmentManager() .findFragmentById(R.id.right_fragment);

Fragment 想回頭找宿主 Activity,則呼叫 getActivity():

 MainActivity activity = (MainActivity) getActivity(); 

五、碎片的生命週期

Fragment 的狀態基本上是跟著宿主 Activity 走的:

運行狀態:Fragment 可見,且關聯的 Activity 處於運行中。
暫停狀態:Activity 進入暫停(例如有另一個未填滿螢幕的 Activity 疊到棧頂),可見的 Fragment 也跟著暫停。
停止狀態:Activity 進入停止時,關聯的 Fragment 也停止。
銷毀狀態:Fragment 依附 Activity 而存在,Activity 被銷毀時 Fragment 隨之銷毀。

幾個常用回呼:

  • onAttach():Fragment 與 Activity 建立關聯時呼叫。
  • onCreateView():為 Fragment 建立視圖(載入布局)時呼叫。
  • onActivityCreated():確保關聯的 Activity 已建立完成時呼叫。
  • onDestroyView():與 Fragment 關聯的視圖被移除時呼叫。
  • onDetach():Fragment 與 Activity 解除關聯時呼叫。

實務上有兩點值得牢記:一是 onDestroyView 與 onDestroy 不同,Fragment 被 replace 或放進返回堆疊時只會走到前者,因此視圖相關的資源釋放該寫在這裡;二是 getActivity() 在 Fragment 已 detach 後會回傳 null,非同步回呼中務必做空值檢查,這是 Fragment 最常見的崩潰來源。新專案中建議直接使用 AndroidX 的 androidx.fragment.app.Fragment,並以 FragmentContainerView 取代 <fragment> 標籤。

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