四大元件之Activity_Fragment

嶽小川發表於2017-02-10

[文章內容來自Developers]

###片段
Fragment表示 Activity中的行為或使用者介面部分。您可以將多個片段組合在一個 Activity 中來構建多窗格 UI,以及在多個 Activity 中重複使用某個片段。您可以將片段視為 Activity 的模組化組成部分,它具有自己的生命週期,能接收自己的輸入事件,並且您可以在 Activity 執行時新增或移除片段(有點像您可以在不同 Activity 中重複使用的“子 Activity”)。
片段必須始終嵌入在 Activity 中,其生命週期直接受宿主 Activity 生命週期的影響。 例如,當 Activity 暫停時,其中的所有片段也會暫停;當 Activity 被銷燬時,所有片段也會被銷燬。 不過,當 Activity 正在執行(處於已恢復生命週期狀態)時,您可以獨立操縱每個片段,如新增或移除它們。 當您執行此類片段事務時,您也可以將其新增到由 Activity 管理的返回棧 — Activity 中的每個返回棧條目都是一條已發生片段事務的記錄。 返回棧讓使用者可以通過按返回按鈕撤消片段事務(後退)。
當您將片段作為 Activity 佈局的一部分新增時,它存在於 Activity 檢視層次結構的某個 ViewGroup內部,並且片段會定義其自己的檢視佈局。您可以通過在 Activity 的佈局檔案中宣告片段,將其作為元素插入您的 Activity 佈局中,或者通過將其新增到某個現有 ViewGroup,利用應用程式碼進行插入。不過,片段並非必須成為 Activity 佈局的一部分;您還可以將沒有自己 UI 的片段用作 Activity 的不可見工作執行緒。
本文描述如何在開發您的應用時使用片段,包括將片段新增到 Activity 返回棧時如何保持其狀態、如何與 Activity 及 Activity 中的其他片段共享事件、如何為 Activity 的操作欄發揮作用等等。

###設計原理

Android 在 Android 3.0(API 級別 11)中引入了片段,主要是為了給大螢幕(如平板電腦)上更加動態和靈活的 UI 設計提供支援。由於平板電腦的螢幕比手機螢幕大得多,因此可用於組合和交換 UI 元件的空間更大。利用片段實現此類設計時,您無需管理對檢視層次結構的複雜更改。 通過將 Activity 佈局分成片段,您可以在執行時修改 Activity 的外觀,並在由 Activity 管理的返回棧中保留這些更改。
例如,新聞應用可以使用一個片段在左側顯示文章列表,使用另一個片段在右側顯示文章 — 兩個片段並排顯示在一個 Activity 中,每個片段都具有自己的一套生命週期回撥方法,並各自處理自己的使用者輸入事件。 因此,使用者不需要使用一個 Activity 來選擇文章,然後使用另一個 Activity 來閱讀文章,而是可以在同一個 Activity 內選擇文章並進行閱讀,如圖 1 中的平板電腦佈局所示。
您應該將每個片段都設計為可重複使用的模組化 Activity 元件。也就是說,由於每個片段都會通過各自的生命週期回撥來定義其自己的佈局和行為,您可以將一個片段加入多個 Activity,因此,您應該採用可複用式設計,避免直接從某個片段直接操縱另一個片段。 這特別重要,因為模組化片段讓您可以通過更改片段的組合方式來適應不同的螢幕尺寸。 在設計可同時支援平板電腦和手機的應用時,您可以在不同的佈局配置中重複使用您的片段,以根據可用的螢幕空間優化使用者體驗。 例如,在手機上,如果不能在同一 Activity 內儲存多個片段,可能必須利用單獨片段來實現單窗格 UI。

四大元件之Activity_Fragment
圖 1. 有關由片段定義的兩個 UI 模組如何適應不同設計的示例:通過組合成一個 Activity 來適應平板電腦設計,通過單獨片段來適應手機設計。
例如 — 仍然以新聞應用為例 — 在平板電腦尺寸的裝置上執行時,該應用可以在 Activity A 中嵌入兩個片段。 不過,在手機尺寸的螢幕上,沒有足以儲存兩個片段的空間,因此Activity A 只包括用於顯示文章列表的片段,當使用者選擇文章時,它會啟動Activity B,其中包括用於閱讀文章的第二個片段。 因此,應用可通過重複使用不同組合的片段來同時支援平板電腦和手機,如圖 1 所示。

###建立片段

四大元件之Activity_Fragment
圖 2. 片段的生命週期(其 Activity 執行時)。

要想建立片段,您必須建立 Fragment的子類(或已有其子類)。Fragment類的程式碼與Activity非常相似。它包含與 Activity 類似的回撥方法,如onCreate()、onStart()、onPause()和 onStop()。實際上,如果您要將現有 Android 應用轉換為使用片段,可能只需將程式碼從 Activity 的回撥方法移入片段相應的回撥方法中。
通常,您至少應實現以下生命週期方法:
onCreate()
系統會在建立片段時呼叫此方法。您應該在實現內初始化您想在片段暫停或停止後恢復時保留的必需片段元件。
onCreateView()
系統會在片段首次繪製其使用者介面時呼叫此方法。 要想為您的片段繪製 UI,您從此方法中返回的 View必須是片段佈局的根檢視。如果片段未提供 UI,您可以返回 null。
onPause()
系統將此方法作為使用者離開片段的第一個訊號(但並不總是意味著此片段會被銷燬)進行呼叫。 您通常應該在此方法內確認在當前使用者會話結束後仍然有效的任何更改(因為使用者可能不會返回)。

大多數應用都應該至少為每個片段實現這三個方法,但您還應該使用幾種其他回撥方法來處理片段生命週期的各個階段。 處理片段生命週期您可能還想擴充套件幾個子類,而不是 Fragment基類:

  • DialogFragment顯示浮動對話方塊。使用此類建立對話方塊可有效地替代使用 Activity類中的對話方塊幫助程式方法,因為您可以將片段對話方塊納入由 Activity 管理的片段返回棧,從而使使用者能夠返回清除的片段。
  • ListFragment顯示由介面卡(如 SimpleCursorAdapter)管理的一系列專案,類似於 ListActivity。它提供了幾種管理列表檢視的方法,如用於處理點選事件的onListItemClick()回撥。
  • PreferenceFragment以列表形式顯示 Preference物件的層次結構,類似於 PreferenceActivity。這在為您的應用建立“設定” Activity 時很有用處。

新增使用者介面
片段通常用作 Activity 使用者介面的一部分,將其自己的佈局融入 Activity。
要想為片段提供佈局,您必須實現 onCreateView()回撥方法,Android 系統會在片段需要繪製其佈局時呼叫該方法。您對此方法的實現返回的View必須是片段佈局的根檢視。
:如果您的片段是 ListFragment的子類,則預設實現會從 onCreateView()返回一個 ListView,因此您無需實現它。
要想從 onCreateView()返回佈局,您可以通過 XML 中定義的佈局資源來擴充套件布局。為幫助您執行此操作,onCreateView()提供了一個LayoutInflater物件。
例如,以下這個 Fragment子類從 example_fragment.xml
檔案載入佈局:

public static class ExampleFragment extends Fragment {    
@Override    
public View onCreateView(LayoutInflater inflater, ViewGroup container,                             Bundle savedInstanceState) {        
// Inflate the layout for this fragment        
return inflater.inflate(R.layout.example_fragment, container, false);    
}}複製程式碼

建立佈局
在上例中,R.layout.example_fragment是對應用資源中儲存的名為example_fragment.xml的佈局資源的引用。
傳遞至 onCreateView()的 container引數是您的片段佈局將插入到的父 ViewGroup(來自 Activity 的佈局)。
savedInstanceState引數是在恢復片段時,提供上一片段例項相關資料的Bundle。
inflate()方法帶有三個引數:

  • 您想要擴充套件的佈局的資源 ID;
  • 將作為擴充套件布局父項的 ViewGroup。傳遞 container對系統向擴充套件布局的根檢視(由其所屬的父檢視指定)應用佈局引數具有重要意義;
  • 指示是否應該在擴充套件期間將擴充套件布局附加至 ViewGroup(第二個引數)的布林值。(在本例中,其值為 false,因為系統已經將擴充套件布局插入 container — 傳遞 true 值會在最終佈局中建立一個多餘的檢視組。)

現在,您已經瞭解瞭如何建立提供佈局的片段。接下來,您需要將該片段新增到您的 Activity 中。
向 Activity 新增片段
通常,片段向宿主 Activity 貢獻一部分 UI,作為 Activity 總體檢視層次結構的一部分嵌入到 Activity 中。可以通過兩種方式向 Activity 佈局新增片段:
在 Activity 的佈局檔案內宣告片段在本例中,您可以將片段當作檢視來為其指定佈局屬性。 例如,以下是一個具有兩個片段的 Activity 的佈局檔案:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    
android:orientation="horizontal"    
android:layout_width="match_parent"    
android:layout_height="match_parent">    
<fragment android:name="com.example.news.ArticleListFragment"     
android:id="@+id/list"            
android:layout_weight="1"            
android:layout_width="0dp"            
android:layout_height="match_parent" />    
<fragment android:name="com.example.news.ArticleReaderFragment"      android:id="@+id/viewer"            
android:layout_weight="2"            
android:layout_width="0dp"            
android:layout_height="match_parent" />
</LinearLayout>複製程式碼

中的 android:name屬性指定要在佈局中例項化的 Fragment類。
當系統建立此 Activity 佈局時,會例項化在佈局中指定的每個片段,併為每個片段呼叫 onCreateView()方法,以檢索每個片段的佈局。系統會直接插入片段返回的 View來替代 元素。

:每個片段都需要一個唯一的識別符號,重啟 Activity 時,系統可以使用該識別符號來恢復片段(您也可以使用該識別符號來捕獲片段以執行某些事務,如將其移除)。 可以通過三種方式為片段提供 ID:

  • 為 android:id屬性提供唯一 ID。
  • 為 android:tag屬性提供唯一字串。
  • 如果您未給以上兩個屬性提供值,系統會使用容器檢視的 ID。

或者通過程式設計方式將片段新增到某個現有 ViewGroup您可以在 Activity 執行期間隨時將片段新增到 Activity 佈局中。您只需指定要將片段放入哪個 ViewGroup。
要想在您的 Activity 中執行片段事務(如新增、移除或替換片段),您必須使用 FragmentTransaction 中的 API。您可以像下面這樣從Activity獲取一個 FragmentTransaction例項:

FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();複製程式碼

然後,您可以使用 add()方法新增一個片段,指定要新增的片段以及將其插入哪個檢視。例如:

ExampleFragment fragment = new ExampleFragment();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();複製程式碼

傳遞到 add()的第一個引數是 ViewGroup,即應該放置片段的位置,由資源 ID 指定,第二個引數是要新增的片段。
一旦您通過 FragmentTransaction 做出了更改,就必須呼叫 commit()以使更改生效。

新增沒有 UI 的片段
上例展示瞭如何向您的 Activity 新增片段以提供 UI。不過,您還可以使用片段為 Activity 提供後臺行為,而不顯示額外 UI。
要想新增沒有 UI 的片段,請使用 add(Fragment, String)從 Activity 新增片段(為片段提供一個唯一的字串“標記”,而不是檢視 ID)。 這會新增片段,但由於它並不與 Activity 佈局中的檢視關聯,因此不會收到對 onCreateView()的呼叫。因此,您不需要實現該方法。
並非只能為非 UI 片段提供字串標記 — 您也可以為具有 UI 的片段提供字串標記 — 但如果片段沒有 UI,則字串標記將是標識它的唯一方式。如果您想稍後從 Activity 中獲取片段,則需要使用 findFragmentByTag()。
如需檢視將沒有 UI 的片段用作後臺工作執行緒的示例 Activity,請參閱 FragmentRetainInstance.java示例,該示例包括在 SDK 示例(通過 Android SDK 管理器提供)中,以/APIDemos/app/src/main/java/com/example/android/apis/app/FragmentRetainInstance.java形式位於您的系統中。

管理片段
要想管理您的 Activity 中的片段,您需要用 FragmentManager。要想獲取它,請從您的 Activity 呼叫 getFragmentManager()。您可以使用 FragmentManager執行的操作包括:

  • 通過 findFragmentById()(對於在 Activity 佈局中提供 UI 的片段)或 findFragmentByTag()(對於提供或不提供 UI 的片段)獲取 Activity 中存在的片段。
  • 通過 popBackStack()(模擬使用者發出的返回命令)將片段從返回棧中彈出。
  • 通過 addOnBackStackChangedListener()註冊一個偵聽返回棧變化的偵聽器。

如上文所示,您也可以使用 FragmentManager開啟一個 FragmentTransaction,通過它來執行某些事務,如新增和移除片段。

執行片段事務
在 Activity 中使用片段的一大優點是,可以根據使用者行為通過它們執行新增、移除、替換以及其他操作。 您提交給 Activity 的每組更改都稱為事務,您可以使用 FragmentTransaction中的 API 來執行一項事務。您也可以將每個事務儲存到由 Activity 管理的返回棧內,從而讓使用者能夠回退片段更改(類似於回退 Activity)。
您可以像下面這樣從 FragmentManager獲取一個 FragmentTransaction例項:

FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();複製程式碼

每個事務都是您想要同時執行的一組更改。您可以使用 add()、remove()和 replace()等方法為給定事務設定您想要執行的所有更改。然後,要想將事務應用到 Activity,您必須呼叫 commit()。
不過,在您呼叫 commit()之前,您可能想呼叫 addToBackStack(),以將事務新增到片段事務返回棧。 該返回棧由 Activity 管理,允許使用者通過按返回按鈕返回上一片段狀態。
例如,以下示例說明了如何將一個片段替換成另一個片段,以及如何在返回棧中保留先前狀態:

// 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 
stacktransaction.replace(R.id.fragment_container, newFragment);transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();複製程式碼

在上例中,newFragment
會替換目前在 R.id.fragment_container
ID 所標識的佈局容器中的任何片段(如有)。通過呼叫 addToBackStack()可將替換事務儲存到返回棧,以便使用者能夠通過按返回按鈕撤消事務並回退到上一片段。
如果您向事務新增了多個更改(如又一個 add()或 remove()),並且呼叫了 addToBackStack(),則在呼叫 commit()前應用的所有更改都將作為單一事務新增到返回棧,並且返回按鈕會將它們一併撤消。
向 FragmentTransaction新增更改的順序無關緊要,不過:
您必須最後呼叫 commit()

如果您要向同一容器新增多個片段,則您新增片段的順序將決定它們在檢視層次結構中的出現順序

如果您沒有在執行移除片段的事務時呼叫 addToBackStack(),則事務提交時該片段會被銷燬,使用者將無法回退到該片段。 不過,如果您在刪除片段時呼叫了 addToBackStack(),則系統會停止該片段,並在使用者回退時將其恢復。
提示:對於每個片段事務,您都可以通過在提交前呼叫 setTransition()來應用過渡動畫。
呼叫 commit()不會立即執行事務,而是在 Activity 的 UI 執行緒(“主”執行緒)可以執行該操作時再安排其線上程上執行。不過,如有必要,您也可以從 UI 執行緒呼叫 executePendingTransactions() 以立即執行 commit() 提交的事務。通常不必這樣做,除非其他執行緒中的作業依賴該事務。
注意:您只能在 Activity[儲存其狀態(使用者離開 Activity)之前使用 commit() 提交事務。如果您試圖在該時間點後提交,則會引發異常。 這是因為如需恢復 Activity,則提交後的狀態可能會丟失。 對於丟失提交無關緊要的情況,請使用 commitAllowingStateLoss()。

###與 Activity 通訊

儘管 Fragment是作為獨立於 Activity的物件實現,並且可在多個 Activity 內使用,但片段的給定例項會直接繫結到包含它的 Activity。
具體地說,片段可以通過 getActivity()訪問 Activity例項,並輕鬆地執行在 Activity 佈局中查詢檢視等任務。

View listView = getActivity().findViewById(R.id.list);複製程式碼

同樣地,您的 Activity 也可以使用 findFragmentById()或 findFragmentByTag(),通過從 FragmentManager獲取對 Fragment的引用來呼叫片段中的方法。例如:

ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment);複製程式碼

建立對 Activity 的事件回撥
在某些情況下,您可能需要通過片段與 Activity 共享事件。執行此操作的一個好方法是,在片段內定義一個回撥介面,並要求宿主 Activity 實現它。 當 Activity 通過該介面收到回撥時,可以根據需要與佈局中的其他片段共享這些資訊。
例如,如果一個新聞應用的 Activity 有兩個片段 — 一個用於顯示文章列表(片段 A),另一個用於顯示文章(片段 B)— 那麼片段 A 必須在列表項被選定後告知 Activity,以便它告知片段 B 顯示該文章。 在本例中,OnArticleSelectedListener
介面在片段 A 內宣告:

public static class FragmentA extends ListFragment {    
...    
// Container Activity must implement this interface    
public interface OnArticleSelectedListener {        
public void onArticleSelected(Uri articleUri);    
}    
...
}複製程式碼

然後,該片段的宿主 Activity 會實現 OnArticleSelectedListener
介面並替代 onArticleSelected()
,將來自片段 A 的事件通知片段 B。為確保宿主 Activity 實現此介面,片段 A 的 onAttach() 回撥方法(系統在向 Activity 新增片段時呼叫的方法)會通過轉換傳遞到 onAttach() 中的 Activity來例項化 OnArticleSelectedListener的例項:

public static class FragmentA extends ListFragment {    
OnArticleSelectedListener mListener;   
 ...    
@Override    
public void onAttach(Activity activity) {        
super.onAttach(activity);        
try {            
mListener = (OnArticleSelectedListener) activity;        
} catch (ClassCastException e) {            
throw new ClassCastException(activity.toString() + " must implement OnArticleSelectedListener");        
}    
}    
...
}複製程式碼

如果 Activity 未實現介面,則片段會引發 ClassCastException。實現時,mListener成員會保留對 Activity 的 OnArticleSelectedListener實現的引用,以便片段 A 可以通過呼叫 OnArticleSelectedListener介面定義的方法與 Activity 共享事件。例如,如果片段 A 是ListFragment的一個擴充套件,則使用者每次點選列表項時,系統都會呼叫片段中的 onListItemClick(),然後該方法會呼叫 onArticleSelected()以與 Activity 共享事件:

public static class FragmentA extends ListFragment {    
OnArticleSelectedListener mListener;    
...    
@Override    
public void onListItemClick(ListView l, View v, int position, long id) {        
// Append the clicked item's row ID with the content provider Uri       
Uri noteUri = ContentUris.withAppendedId(ArticleColumns.CONTENT_URI, id);        
// Send the event and Uri to the host activity        
mListener.onArticleSelected(noteUri);    
}    
...
}複製程式碼

傳遞到 onListItemClick()的 id
引數是被點選項的行 ID,即 Activity(或其他片段)用來從應用的 ContentProvider獲取文章的 ID。

嚮應用欄新增專案
您的片段可以通過實現 onCreateOptionsMenu()向 Activity 的選項選單(並因此嚮應用欄貢獻選單項。不過,為了使此方法能夠收到呼叫,您必須在 onCreate()期間呼叫 setHasOptionsMenu(),以指示片段想要向選項選單新增選單項(否則,片段將不會收到對onCreateOptionsMenu()的呼叫)。
您之後從片段新增到選項選單的任何選單項都將追加到現有選單項之後。 選定選單項時,片段還會收到對 onOptionsItemSelected()的回撥。
您還可以通過呼叫 registerForContextMenu(),在片段佈局中註冊一個檢視來提供上下文選單。使用者開啟上下文選單時,片段會收到對onCreateContextMenu()的呼叫。當使用者選擇某個選單項時,片段會收到對 onContextItemSelected()的呼叫。
:儘管您的片段會收到與其新增的每個選單項對應的選單項選定回撥,但當使用者選擇選單項時,Activity 會首先收到相應的回撥。 如果 Activity 對選單項選定回撥的實現不會處理選定的選單項,則系統會將事件傳遞到片段的回撥。 這適用於選項選單和上下文選單。

###處理片段生命週期

四大元件之Activity_Fragment
圖 3. Activity 生命週期對片段生命週期的影響。

管理片段生命週期與管理 Activity 生命週期很相似。和 Activity 一樣,片段也以三種狀態存在:
繼續
片段在執行中的 Activity 中可見。
暫停
另一個 Activity 位於前臺並具有焦點,但此片段所在的 Activity 仍然可見(前臺 Activity 部分透明,或未覆蓋整個螢幕)。
停止
片段不可見。宿主 Activity 已停止,或片段已從 Activity 中移除,但已新增到返回棧。 停止片段仍然處於活動狀態(系統會保留所有狀態和成員資訊)。 不過,它對使用者不再可見,如果 Activity 被終止,它也會被終止。

同樣與 Activity 一樣,假使 Activity 的程式被終止,而您需要在重建 Activity 時恢復片段狀態,您也可以使用 Bundle 保留片段的狀態。您可以在片段的 onSaveInstanceState()回撥期間儲存狀態,並可在onCreate()、onCreateView()或 onActivityCreated()期間恢復狀態。
Activity 生命週期與片段生命週期之間的最顯著差異在於它們在其各自返回棧中的儲存方式。 預設情況下,Activity 停止時會被放入由系統管理的 Activity 返回棧(以便使用者通過返回按鈕回退到 Activity,任務和返回棧對此做了闡述)。不過,僅當您在移除片段的事務執行期間通過呼叫 addToBackStack())顯式請求儲存例項時,系統才會將片段放入由宿主 Activity 管理的返回棧。
在其他方面,管理片段生命週期與管理 Activity 生命週期非常相似。 因此,管理 Activity 生命週期的做法同樣適用於片段。 但您還需要了解 Activity 的生命週期對片段生命週期的影響。
注意:如需 Fragment 內的某個 Context物件,可以呼叫 getActivity()。但要注意,請僅在片段附加到 Activity 時呼叫getActivity()。如果片段尚未附加,或在其生命週期結束期間分離,則 getActivity()將返回 null。

與 Activity 生命週期協調一致
片段所在的 Activity 的生命週期會直接影響片段的生命週期,其表現為,Activity 的每次生命週期回撥都會引發每個片段的類似回撥。 例如,當 Activity 收到 onPause()時,Activity 中的每個片段也會收到 onPause()。
不過,片段還有幾個額外的生命週期回撥,用於處理與 Activity 的唯一互動,以執行構建和銷燬片段 UI 等操作。 這些額外的回撥方法是:

  • onAttach()
    在片段已與 Activity 關聯時呼叫(Activity傳遞到此方法內)。
  • onCreateView()
    呼叫它可建立與片段關聯的檢視層次結構。
  • onActivityCreated()
    在 Activity 的 onCreate()方法已返回時呼叫。
  • onDestroyView()
    在移除與片段關聯的檢視層次結構時呼叫。
  • onDetach()
    在取消片段與 Activity 的關聯時呼叫。

圖 3 圖示說明了受其宿主 Activity 影響的片段生命週期流。在該圖中,您可以看到 Activity 的每個連續狀態如何決定片段可以收到的回撥方法。 例如,當 Activity 收到其 onCreate() 回撥時,Activity 中的片段只會收到 onActivityCreated() 回撥。
一旦 Activity 達到恢復狀態,您就可以隨意向 Activity 新增片段和移除其中的片段。 因此,只有當 Activity 處於恢復狀態時,片段的生命週期才能獨立變化。
不過,當 Activity 離開恢復狀態時,片段會在 Activity 的推動下再次經歷其生命週期。
示例
為了將本文闡述的所有內容融會貫通,以下提供了一個示例,其中的 Activity 使用兩個片段來建立一個雙窗格佈局。 下面的 Activity 包括兩個片段:一個用於顯示莎士比亞戲劇標題列表,另一個用於從列表中選定戲劇時顯示其摘要。 此外,它還展示瞭如何根據螢幕配置提供不同的片段配置。
FragmentLayout.java 中提供了此 Activity 的完整原始碼。
主 Activity 會在 onCreate()期間以常規方式應用佈局:

@Override
protected void onCreate(Bundle savedInstanceState) {    
super.onCreate(savedInstanceState);    
setContentView(R.layout.fragment_layout);
}複製程式碼

應用的佈局為 fragment_layout.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    
android:orientation="horizontal"    
android:layout_width="match_parent" 
android:layout_height="match_parent">    
<fragment class="com.example.android.apis.app.FragmentLayout$TitlesFragment"            
android:id="@+id/titles" android:layout_weight="1"            
android:layout_width="0px" 
android:layout_height="match_parent" />    
<FrameLayout android:id="@+id/details" 
android:layout_weight="1"            
android:layout_width="0px" 
android:layout_height="match_parent"            
android:background="?android:attr/detailsElementBackground" />
</LinearLayout>複製程式碼

通過使用此佈局,系統可在 Activity 載入佈局時立即例項化 TitlesFragment
(列出戲劇標題),而 FrameLayout(用於顯示戲劇摘要的片段所在位置)則會佔用螢幕右側的空間,但最初處於空白狀態。 正如您將在下文所見的那樣,使用者從列表中選擇某個專案後,系統才會將片段放入FrameLayout。
不過,並非所有螢幕配置都具有足夠的寬度,可以並排顯示戲劇列表和摘要。 因此,以上佈局僅用於橫向螢幕配置(佈局儲存在 res/layout-land/fragment_layout.xml)。
因此,當螢幕縱向顯示時,系統會應用以下佈局(儲存在 res/layout/fragment_layout.xml):

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"    
android:layout_width="match_parent" 
android:layout_height="match_parent">    
<fragment class="com.example.android.apis.app.FragmentLayout$TitlesFragment"            
android:id="@+id/titles"            
android:layout_width="match_parent" 
android:layout_height="match_parent" />
</FrameLayout>複製程式碼

此佈局僅包括 TitlesFragment。這意味著,當裝置縱向顯示時,只有戲劇標題列表可見。 因此,當使用者在此配置中點選某個列表項時,應用會啟動一個新 Activity 來顯示摘要,而不是載入另一個片段。
接下來,您可以看到如何在片段類中實現此目的。第一個片段是 TitlesFragment,它顯示莎士比亞戲劇標題列表。該片段擴充套件了 ListFragment,並依靠它來處理大多數列表檢視工作。
當您檢查此程式碼時,請注意,使用者點選列表項時可能會出現兩種行為:系統可能會建立並顯示一個新片段,從而在同一 Activity 中顯示詳細資訊(將片段新增到 FrameLayout),也可能會啟動一個新 Activity(在該 Activity 中可顯示片段),具體取決於這兩個佈局中哪一個處於活動狀態。

public static class TitlesFragment extends ListFragment {    
boolean mDualPane;    
int mCurCheckPosition = 0;    
@Override    
public void onActivityCreated(Bundle savedInstanceState) {        
super.onActivityCreated(savedInstanceState);        
// Populate list with our static array of titles.        
setListAdapter(new ArrayAdapter<String>(getActivity(),                android.R.layout.simple_list_item_activated_1, Shakespeare.TITLES));        
// Check to see if we have a frame in which to embed the details        
// fragment directly in the containing UI.        
View detailsFrame = getActivity().findViewById(R.id.details);      
  mDualPane = detailsFrame != null && 
detailsFrame.getVisibility() == View.VISIBLE;        
if (savedInstanceState != null) {            
// Restore last state for checked position.            
mCurCheckPosition = savedInstanceState.getInt("curChoice", 0);        
}        
if (mDualPane) {            
// In dual-pane mode, the list view highlights the selected item. getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);            
// Make sure our UI is in the correct state.            
showDetails(mCurCheckPosition);        
}    
}    
@Override    
public void onSaveInstanceState(Bundle outState) {        
super.onSaveInstanceState(outState);        
outState.putInt("curChoice", mCurCheckPosition);    
}    
@Override    
public void onListItemClick(ListView l, View v, int position, long id) {        
showDetails(position);    
}    
/**     
* Helper function to show the details of a selected item, either by     
* displaying a fragment in-place in the current UI, or starting a    
 * whole new activity in which it is displayed.     
*/    
void showDetails(int index) {        
mCurCheckPosition = index;        
if (mDualPane) {            
// We can display everything in-place with fragments, so update  
          // the list to highlight the selected item and show the data.            
getListView().setItemChecked(index, true);            
// Check what fragment is currently shown, replace if needed.    
        DetailsFragment details = (DetailsFragment)                    getFragmentManager().findFragmentById(R.id.details);            
if (details == null || details.getShownIndex() != index) {                
// Make new fragment to show this selection.                
details = DetailsFragment.newInstance(index);                
// Execute a transaction, replacing any existing fragment            
    // with this one inside the frame.                
FragmentTransaction ft = getFragmentManager().beginTransaction();                
if (index == 0) {                    
ft.replace(R.id.details, details);                
} else {                    
ft.replace(R.id.a_item, details);                
}                
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);                
ft.commit();            
}        
} else {            
// Otherwise we need to launch a new activity to display            
// the dialog fragment with selected text.            
Intent intent = new Intent();            
intent.setClass(getActivity(), DetailsActivity.class);            
intent.putExtra("index", index);            
startActivity(intent);        
}    
}}複製程式碼

第二個片段 DetailsFragment顯示從 TitlesFragment的列表中選擇的專案的戲劇摘要:

public static class DetailsFragment extends Fragment {    
/**     
* Create a new instance of DetailsFragment, initialized to     
* show the text at 'index'.     
*/    
public static DetailsFragment newInstance(int index) {        
DetailsFragment f = new DetailsFragment();        
// Supply index input as an argument.        
Bundle args = new Bundle();        
args.putInt("index", index);        
f.setArguments(args);        
return f;    
}    
public int getShownIndex() {        
return getArguments().getInt("index", 0);    
}    
@Override    
public View onCreateView(LayoutInflater inflater, ViewGroup container,            Bundle savedInstanceState) {        
if (container == null) {            
// We have different layouts, and in one of them this            
// fragment's containing frame doesn't exist.  The fragment          
  // may still be created from its saved state, but there is            
// no reason to try to create its view hierarchy because it            
// won't be displayed.  Note this is not needed -- we could            
// just run the code below, where we would create and return      
      // the view hierarchy; it would just never be used.            
return null;        
}        
ScrollView scroller = new ScrollView(getActivity());        
TextView text = new TextView(getActivity());        
int padding = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,                4, getActivity().getResources().getDisplayMetrics());        
text.setPadding(padding, padding, padding, padding);        
scroller.addView(text);        
text.setText(Shakespeare.DIALOGUE[getShownIndex()]);        
return scroller;    
}}複製程式碼

從 TitlesFragment類中重新呼叫,如果使用者點選某個列表項,且當前佈局“根本不”**包括 R.id.details檢視(即 DetailsFragment
所屬檢視),則應用會啟動 DetailsActivity Activity 以顯示該專案的內容。
以下是 DetailsActivity,它簡單地嵌入了 DetailsFragment,以在螢幕為縱向時顯示所選的戲劇摘要:

public static class DetailsActivity extends Activity {    
@Override    
protected void onCreate(Bundle savedInstanceState) {        
super.onCreate(savedInstanceState);        
if (getResources().getConfiguration().orientation  == Configuration.ORIENTATION_LANDSCAPE) {            

// If the screen is now in landscape mode, we can show the            // dialog in-line with the list so we don't need this activity.        
    finish();            
return;        
}        
if (savedInstanceState == null) {            
// During initial setup, plug in the details fragment.            
DetailsFragment details = new DetailsFragment();            
details.setArguments(getIntent().getExtras());            
getFragmentManager().beginTransaction().add(android.R.id.content, details).commit();        
}    
}}複製程式碼

請注意,如果配置為橫向,則此 Activity 會自行完成,以便主 Activity 可以接管並沿 TitlesFragment顯示 DetailsFragment。如果使用者在縱向顯示時啟動 DetailsActivity,但隨後旋轉為橫向(這會重啟當前 Activity),就可能出現這種情況。

相關文章