2013-10-18 94 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> 框架布局是一种视图组,用于屏蔽屏幕上的区域。

相关问题