【发布时间】: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用于一个replace和R.id.forgot_password_email_fragment用于另一个。这些不是同一个容器。您的意思是它们是完全独立的容器吗?
标签: android android-fragments android-fragmentactivity