Android: when/why should I use FrameLayout instead of Fragment?

Ter*_*rry 43 android android-fragments android-framelayout

I am building a layout for large screens, that is supposed to consist of 2 different parts, a left one and a right one. For doing that I thought using 2 Fragments is the right choice.

Then I had a look on the example of the navigation with the Master/Detail-Flow. It has a 2-pane layout, where on the right is the navigation, and on the left is the detail view.

但是在那个例子中,与我期望看到的不同,对于细节视图,有一个FrameLayout然后持有a 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>
Run Code Online (Sandbox Code Playgroud)

我现在的问题是:为什么在详细视图中FrameLayout使用而不是Fragment自己?是什么原因或优势?我也应该用它吗?

Tan*_*.7x 39

细节容器是FrameLayout因为Fragment所显示将被替换使用FragmentTransactionreplace()方法.

第一个参数replace()是要替换Fragments的容器的ID.如果此示例中的FrameLayout被片段替换,则WorkStationListFragment当前显示的片段和任何细节片段都将被新片段替换.通过将Fragment封装在FrameLayout中,您可以只替换细节.


Sur*_*nav 6

fragment标签:可用于通过XML立即加载fragment,但不能通过transaction.replace()方法替换。可以按名称或类属性加载片段。

FrameLayout 标签:只能通过编程方式加载片段,并且片段可以通过 transaction.replace() 方法替换。可以通过FragmentTransction添加/替换fragment。

FragmentContainerView 标签: FragmentContainerView 是 FrameLayout 的子级,也是最推荐的加载片段的视图,它支持片段标签的属性:(名称和类),因此可以从 XML 加载片段,但与片段标签不同的是,片段可以通过事务替换。代替()。我们知道它是 FrameLayout 的子级,因此支持 FrameLayout 的所有功能,我们可以像在 FrameLayout 中一样添加片段。

此外,FragmentCotainerView 中还解决了 FrameLayout 的动画相关问题:

以前,尝试自定义 Fragment 的进入和退出动画会导致出现以下问题:进入的 Fragment 将位于退出的 Fragment 下方,直到完全退出屏幕。当片段之间转换时,这会导致令人不快且错误的动画。

检查此链接