问题描述
我正在为大屏幕构建一个布局,它应该由 2 个不同的部分组成,一个左一个右一个.为此,我认为使用 2 Fragments 是正确的选择.
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.
然后我查看了带有 Master/Detail-Flow 的导航示例.它有一个 2 窗格布局,右侧是导航,左侧是详细信息视图.
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
然后保存一个 Fragment
,而不是一个 直接分片
.
But in that example, different from what I expected to see, for the detail view there is a FrameLayout
that then holds a Fragment
, instead of a Fragment
directly.
布局 XML 如下所示(示例):
The layout XML looks like this (an example):
<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>
我现在的问题是:为什么在详细视图中使用 FrameLayout
而不是 Fragment
本身?原因或优势是什么?我也应该使用它吗?
My question now is: why is a FrameLayout
used instead of the Fragment
itself for the detail view? What is the reason or the advantage? Should I use it too?
推荐答案
detail 容器是 FrameLayout
因为显示的 Fragment
将使用 替换FragmentTransaction
的 replace()
方法.
The detail container is a FrameLayout
because the Fragment
that is displayed will be replaced using FragmentTransaction
's replace()
method.
replace()
的第一个参数是其片段将被替换的容器的 ID.如果此示例中的 FrameLayout 被 Fragment 替换,则 WorkStationListFragment
和当前显示的任何细节 Fragment 都将被新的 Fragment 替换.通过将 Fragment 封装在 FrameLayout 中,您可以只替换细节.
The first argument to replace()
is the ID of container whose Fragments will be replaced. If the FrameLayout in this example were replaced with a Fragment, then both the WorkStationListFragment
and whatever detail Fragment is currently shown would be replaced by the new Fragment. By encapsulating the Fragment within a FrameLayout, you can replace just the details.
这篇关于Android:何时/为什么我应该使用 FrameLayout 而不是 Fragment?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!