两个片段,两个不同的布局,一个 activity

Two Fragments, two different layouts, one activity

我有一个 activity,它在 RelativeLayout 中开始运行片段 A,

在那之后,在这个片段中,我尝试打开另一个片段 B,不知何故它只是一个叠加层,它在另一个 RelativeLayout 中运行,以查看片段 A 上方,到目前为止,一切正常,但问题是在 onBackPressed():

我打开覆盖片段 B,然后我按下后退按钮,但它只关闭了片段 A。

这是我的 activity 的 xml

<RelativeLayout
    android:id="@+id/main_fragment_replacement"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</RelativeLayout>

<RelativeLayout
    android:background="#0000"
    android:id="@+id/overlay_fragment_replacement"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

我认为这应该可以解释,但我想提供任何其他信息。

您可以使用标签。在打开片段 B 之前,将标签设置为等于 "a"。 覆盖 onBackPressed() 方法并检查标签的值。如果等于"a"则打开片段a。如果它等于 "b" 然后打开片段 b.

添加片段时,您可以将它们添加到后台。

getSupportManager()
        .beginTransaction()
        .replace(R.id.container, fragment)
        .addToBackStack(null)
        .commit();

然后您可以简单地检查 多少 片段在您的后台堆栈中并删除例如片段 B 当 2 当 backstack 包含两个片段时。

android documentation for Fragments中提到了这个过程。

If you don't call addToBackStack() when you perform a transaction that removes a fragment, then that fragment is destroyed when the transaction is committed and the user cannot navigate back to it. Whereas, if you do call addToBackStack() when removing a fragment, then the fragment is stopped and is later resumed if the user navigates back.