【问题标题】:Fragment not replaced when using replace()使用 replace() 时片段未替换
【发布时间】:2021-11-17 11:07:03
【问题描述】:

我创建了一个包含 2 个片段的活动。 两个片段都显示在相同的活动布局中。

活动布局:

<androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/main_container"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:orientation="vertical"
        app:layout_constraintTop_toBottomOf="@+id/toolbar"
        app:layout_constraintBottom_toBottomOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

首先加载第一个片段,它运行良好。

我正在使用此命令加载main_container 中的第一个片段

    replaceFragment(ForgotPasswordEmailFragment(), R.id.main_container)

ForgotPasswordEmailFragment 包含一个按钮,当我单击它时,它假设通过使用以下代码将这个片段替换为新片段来加载另一个片段:

val forgotPasswordNewPasswordFragment: Fragment = ForgotPasswordNewPasswordFragment()
        val fragmentTransaction: FragmentTransaction = parentFragmentManager.beginTransaction()
        fragmentTransaction.replace(R.id.forgot_password_email_fragment, forgotPasswordNewPasswordFragment)
        fragmentTransaction.addToBackStack(null)
        fragmentTransaction.commit()

ForgotPasswordNewPasswordFragment 被加载时,我正在使用下面的代码加载新布局:

fragmentForgotPasswordNewPasswordBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_forgot_password_new_password, container, false)
        return fragmentForgotPasswordNewPasswordBinding.root

发生的情况是ForgotPasswordEmailFragment 的布局仍然存在,ForgotPasswordNewPasswordFragment 的布局也显示出来了。片段根本没有被替换

知道为什么吗?

【问题讨论】:

  • 您将R.id.main_container 用于一个replaceR.id.forgot_password_email_fragment 用于另一个。这些不是同一个容器。您的意思是它们是完全独立的容器吗?

标签: android android-fragments android-fragmentactivity


【解决方案1】:

在替换任何片段时,您必须使用相同的容器 ID。即main_container

val forgotPasswordNewPasswordFragment: Fragment = ForgotPasswordNewPasswordFragment()
        val fragmentTransaction: FragmentTransaction = parentFragmentManager.beginTransaction()
        fragmentTransaction.replace(R.id.main_container, forgotPasswordNewPasswordFragment)
        fragmentTransaction.addToBackStack(null)
        fragmentTransaction.commit()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-10
    • 1970-01-01
    • 1970-01-01
    • 2019-02-06
    • 1970-01-01
    • 2012-04-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多