我正在为大屏幕构建一个布局,它应该由两个不同的部分组成,一个左边和一个右边。为此,我认为使用 2 个片段是正确的选择。
然后,我查看了使用主/细节流进行导航的示例。它具有 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>
我现在的问题是:为什么使用FrameLayout
而不是Fragment
本身来获取详细信息视图?原因或优势是什么?我也应该使用它吗?
详细信息容器是一个FrameLayout
,因为显示的Fragment
将使用FragmentTransaction
的replace()
方法替换。
要replace()
的第一个参数是将替换其片段的容器的 ID。如果此示例中的 FrameLayout 被替换为片段,则WorkStationListFragment
和当前显示的任何细节片段都将替换为新的片段。通过将片段封装在框架布局中,您可以只替换细节。
fragment tag:可用于通过XML立即加载片段,但不能被transaction.replace()方法取代。可以按名称或类属性加载片段。
FrameLayout 标签:只能通过编程方式加载片段,片段也可以用 transaction.replace() 方法替换。可以通过片段转换添加/替换片段。
FragmentContainerView 标签:FragmentContainerView 是 FrameLayout 的子级,也是最推荐加载片段的视图,它支持片段标签的属性:(名称和类),因此片段可以从 XML 加载,但与片段标签不同的是,片段可以用 transaction.replace() 替换。众所周知,它是FrameLayout的子级,因此支持FrameLayout的所有功能,我们可以像在FrameLayout中一样添加片段。
此外,FrameLayout的动画相关问题在FragmentCotainerView中得到解决:
以前,尝试自定义 的进入和退出动画 片段导致输入片段的问题 在退出片段下方,直到它完全退出屏幕。 这导致了令人不快和错误的动画,当 在片段之间转换。
检查此链接。