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

用 FragmentManager 管理 Android fragments

編輯:Android 資訊

Fragment 的動態管理是 Android 開發中相當核心的一塊,而這件事主要交給 FragmentManager 負責。本文從 FragmentManager 的基礎談起,說明 FragmentTransaction 的用法,最後以一個可運行的範例收尾。

FragmentManager

要管理 Activity 中的 fragments,就需要 FragmentManager。取得方式是呼叫 Activity 的 getFragmentManager()。

需要注意的是,FragmentManager 的 API 從 Android 3.0(API level 11)才開始提供。若需相容更早的版本,必須改用 support library 中的 FragmentActivity,並以 getSupportFragmentManager() 取得。

FragmentManager 能做的工作:

取得 Activity 中既有的 fragment:使用 findFragmentById() 或 findFragmentByTag()。

把 fragment 移出 back stack:呼叫 popBackStack(),會把 stack 中最後一次的轉換彈出;若沒有可彈出的內容則回傳 false。要注意這個方法是非同步的——它只是把請求排入佇列,實際動作要等到應用回到事件迴圈時才執行。

為 back stack 加上監聽器:呼叫 addOnBackStackChangedListener()。

Fragment Transactions

使用 Fragment 時,常需要依使用者操作來新增、移除或替換它。這一連串變更會被當成一個集合,稱為一個 transaction。

取得 FragmentTransaction 實例的方式如下:

FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

每個 transaction 是一組會同時生效的變更集合。用 add()、remove()、replace() 把所有需要的變更加進去,最後呼叫 commit() 套用。

在 commit() 之前,可以呼叫 addToBackStack() 把這個 transaction 存進由 Activity 管理的 back stack,這樣使用者按返回鍵時就能回到 fragment 變更前的狀態。

以下程式碼示範用一個新 fragment 取代舊的,並把前一個狀態存進 back stack:

// Create new fragment and transaction Fragment newFragment = new ExampleFragment(); FragmentTransaction transaction = getFragmentManager().beginTransaction(); // Replace whatever is in the fragment_container view with this fragment, // and add the transaction to the back stack transaction.replace(R.id.fragment_container, newFragment); transaction.addToBackStack(null); // Commit the transaction transaction.commit();

這段程式會讓 newFragment 取代 R.id.fragment_container 容器中原有的 fragment;若容器裡本來沒有東西,則直接放入新 fragment。透過 addToBackStack(),這一系列變更會作為一個整體被記錄下來,使用者按返回鍵即可回到轉換前的畫面。

移除 fragment 時也有類似邏輯:若 commit() 之前沒有呼叫 addToBackStack(),該 fragment 會被直接銷毀;若呼叫了,則它會進入 stopped 狀態,使用者可以按返回鍵恢復。

關於 commit()

呼叫 commit() 並不會立刻執行 transaction 中的變更,它只是把這個 transaction 放進 Activity 的 UI 執行緒佇列。若確有必要,可以呼叫 executePendingTransactions() 讓它馬上執行;但通常不需要這麼做,除非這個 transaction 被其他執行緒依賴。

還有一點很重要:commit() 必須在 Activity 儲存自身狀態(即使用者即將離開時)之前呼叫。若在儲存狀態之後才呼叫,會丟出例外。這是因為 Activity 再次還原時,commit 之後的狀態已經遺失。如果這種遺失可以接受,可以改用 commitAllowingStateLoss()。

範例程式

寫了一個小程式來實作 fragment 的管理:第一個按鈕新增一個 fragment,第二個按鈕把它替換掉,第三個按鈕則移除第二個按鈕加入的那個。

第一個 fragment:

package com.example.learningfragment; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class ExampleFragment extends Fragment { //三個一般必須重載的方法 @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); System.out.println("ExampleFragment--onCreate"); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { System.out.println("ExampleFragment--onCreateView"); return inflater.inflate(R.layout.example_fragment_layout, container, false); } @Override public void onPause() { super.onPause(); System.out.println("ExampleFragment--onPause"); } @Override public void onResume() { super.onResume(); System.out.println("ExampleFragment--onResume"); } @Override public void onStop() { super.onStop(); System.out.println("ExampleFragment--onStop"); } }

它的版面:

<?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="match_parent" android:layout_height="wrap_content" android:gravity="left" android:textSize="20dip" android:text="@string/fragment1" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/num1" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/num2" /> </LinearLayout>

第二個 fragment:

package com.example.learningfragment; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class NewFragment extends Fragment { //三個一般必須重載的方法 @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); System.out.println("NewFragment--onCreate"); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { System.out.println("NewFragment--onCreateView"); return inflater.inflate(R.layout.new_fragment_layout, container, false); } @Override public void onPause() { super.onPause(); System.out.println("NewFragment--onPause"); } }
<?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="match_parent" android:layout_height="wrap_content" android:textSize="20dip" android:gravity="left" android:text="@string/fragment2" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/num3" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/num4" /> </LinearLayout>

主 Activity:

package com.example.learningfragment; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.view.View; import android.widget.Button; public class LearnFragment extends FragmentActivity { Button btn1; Button btn2; Button btn3; ExampleFragment fragmentE; NewFragment fragmentN; FragmentManager fragmentManager; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_learn_fragment); findViews(); setListeners(); //獲得Fragment管理所需要的類的對象 fragmentManager = getSupportFragmentManager(); } private void findViews() { btn1 = (Button) findViewById(R.id.btn1); btn2 = (Button) findViewById(R.id.btn2); btn3 = (Button) findViewById(R.id.btn3); } private void setListeners() { //第一個按鈕,增加一個ExampleFragment btn1.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { //在程序中加入ExampleFragment fragmentE = new ExampleFragment(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.add(R.id.linear1,fragmentE); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); } } ); //第二個按鈕,用一個NewFragment替換前面增加的那個fragment btn2.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { fragmentN = new NewFragment(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.linear1,fragmentN); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); } } ); //第三個按鈕,移除fragment btn3.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.remove(fragmentN); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); } } ); } }
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools" android:id="@+id/linear1" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="20dip" android:gravity="center_horizontal" android:text="@string/layout1" /> <Button android:id="@+id/btn1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/btn1" /> <fragment android:name="com.example.learningfragment.ExampleFragment" android:id="@+id/fragment1" android:layout_width="match_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/btn2" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/btn2" /> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:id="@+id/linear2" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical" > <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="20dip" android:gravity="center_horizontal" android:text="@string/layout2" /> <Button android:id="@+id/btn3" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/btn3" /> </LinearLayout> </LinearLayout>

資源檔:

<resources> <string name="app_name">LearningFragment</string> <string name="hello_world">Hello world!</string> <string name="menu_settings">Settings</string> <string name="title_activity_learn_fragment">LearnFragment</string> <string name="layout1">LinearLayout1</string> <string name="layout2">LinearLayout2</string> <string name="fragment1">FragmentType1</string> <string name="fragment2">FragmentType2</string> <string name="num1">NO.1</string> <string name="num2">NO.2</string> <string name="num3">NO.3</string> <string name="num4">NO.4</string> <string name="btn1">Add fragment</string> <string name="btn2">Replace fragment</string> <string name="btn3">Remove fragment</string> </resources>

執行結果:

這個範例刻意在各個生命週期方法中印出訊息,方便觀察 add、replace、remove 分別觸發了哪些回呼。實作時可以發現一個重點:三個操作都伴隨 addToBackStack(null),因此按返回鍵能逐步回退。若某個操作不該被回退(例如初始化時載入第一個 fragment),就應該省略 addToBackStack(),否則使用者按返回鍵時會出現意料之外的畫面跳動。

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