2013-10-18 48 views
37

我正在構建一個大屏幕布局,應該由兩個不同的部分組成,一個左邊和一個右邊。爲了做到這一點,我認爲使用2片段是正確的選擇。Android:何時/爲什麼我應該使用FrameLayout而不是Fragment?

然後我看了一個Master/Detail-Flow導航的例子。它有一個2窗格佈局,其中右側是導航,左側是詳細視圖。

但是在那個例子中,與我期望看到的不同,對於詳細視圖,有一個FrameLayout,然後直接持有Fragment而不是Fragment

佈局XML看起來是這樣的(例子):

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:layout_marginLeft="16dp" 
    android:layout_marginRight="16dp" 
    android:baselineAligned="false" 
    android:divider="?android:attr/dividerHorizontal" 
    android:orientation="horizontal" 
    android:showDividers="middle" 
    tools:context=".WorkStationListActivity" > 

    <fragment 
     android:id="@+id/workstation_list" 
     android:name="de.tuhh.ipmt.ialp.history.WorkStationListFragment" 
     android:layout_width="0dp" 
     android:layout_height="match_parent" 
     android:layout_weight="1" 
     tools:layout="@android:layout/list_content" /> 

    <FrameLayout 
     android:id="@+id/workstation_detail_container" 
     android:layout_width="0dp" 
     android:layout_height="match_parent" 
     android:layout_weight="3" /> 

</LinearLayout> 

我現在的問題是:爲什麼是用來代替Fragment本身的細節視圖FrameLayout?原因或優勢是什麼?我是否也應該使用它?

回答

36

詳細信息容器是FrameLayout,因爲顯示的Fragment將使用FragmentTransactionreplace()方法替換。

replace()的第一個參數是其碎片將被替換的容器的ID。如果此示例中的FrameLayout被替換爲片段,則WorkStationListFragment和當前顯示的任何細節片段都將被新片段替換。通過將該片段封裝在FrameLayout中,您可以僅替換細節。

+0

確實有幫助。在我的情況下,我不需要替換片段,所以現在我知道我可以離開'FrameLayout'並直接使用'Fragment'。 – Terry

2

如果您不需要它來響應用戶界面中的更改,請使用<fragment>向活動添加片段。否則,請使用<FrameLayout> 框架佈局是一種視圖組,用於屏蔽屏幕上的區域。

相關問題