gpt4 book ai didi

android:替换 CoordinatorLayout 内的 fragment 容器

转载 作者:行者123 更新时间:2023-11-29 01:19:41 25 4
gpt4 key购买 nike

我有以下 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 时,它不起作用,它显示新 fragment 但也保留旧 fragment ,在我的简单示例中,带有 Hello world 的 TextView 将保留。

要替换,我使用以下代码:

FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.content_main, fragment);
transaction.commit();

有什么想法吗?

最佳答案

FragmentTransaction我们只处理 Fragment s 和他们的 View秒。 TextView您在布局中定义的不是(的一部分)FragmentView , 所以它不会受到 FragmentTransaction 的影响, 和 Fragment在您的代码段中将被添加到它的顶部。

您有几个选择。您可以隐藏或删除 TextView执行交易时自己。这可能更可取,如果那么简单 TextView是您最初需要的,并将其粘贴在 Fragment 中可能是矫枉过正。您也可以简单地在 Fragment 上设置不透明背景。的布局,这将有效地隐藏 TextView .

然而,最好的选择可能是将 TextView在另一个布局中Fragment在启动时加载。随后的交易将按照您的预期替换/删除它。请注意任何 Fragment您希望在运行时替换/删除必须在您的代码中动态加载。也就是说,它们不能在 <fragment> 中定义Activity 中的元素的布局。

关于android:替换 CoordinatorLayout 内的 fragment 容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37668129/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com