【发布时间】:2016-06-06 23:05:47
【问题描述】:
我有以下 XML:
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<!--I use this include as container with the FrameLayout below-->
<!--<include layout="@layout/content_main" />-->
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/content_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.improvemybrand.MainActivity"
tools:showIn="@layout/app_bar_main">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</FrameLayout>
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
android:src="@android:drawable/ic_input_add" />
问题很简单:
当我尝试从 Coordinator 替换容器 FrameLayout 时,它不起作用,它显示新片段但也保留旧片段,在我的简单示例中,带有 Hello world 的 TextView 将保留。
要替换,我使用以下代码:
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.content_main, fragment);
transaction.commit();
有什么想法吗?
【问题讨论】:
-
TextView不是Fragment的View,所以它不会受到FragmentTransaction的影响。 -
编辑:@MikeM。我应该将 TextView 包装在片段中并选择要替换的片段吗?
-
我不确定你的意思,但
FragmentTransactions 只处理Fragments 和他们的Views。如果您愿意,您可以将TextView设为另一个Fragment的View,或其中的一部分,然后事务将相应地替换它。或者,如果它不需要成为Fragment的一部分,您可以自行删除或隐藏它。 -
@MikeM。我想我明白了......我必须从 XML 中删除 TextView,如果我真的想要,我必须在 onCreate 中以编程方式添加,然后 FragmentTransaction 将在我的容器中添加片段。我会做一些测试,让你知道。谢谢。
-
没问题。我应该提一下,您要替换/删除的任何
Fragment都必须动态加载——即,not 定义为布局 XML 中的<fragment>元素——但听起来这就是你的计划。