Android 销毁所有碎片后显示空白活动

Android 销毁所有碎片后显示空白活动,android,android-layout,android-fragments,Android,Android Layout,Android Fragments,我已经创建了一个主活动,其中包含一个片段容器,我正在导航菜单选项选择中替换其中的许多片段。工作正常,但问题是: 当我两次单击导航项时,两个相同的片段打开,我必须按两次后退按钮才能返回 当按下back键后所有的片段都被销毁时,我看到一个空页面(我猜这可能是主活动页面) layout\u main.xml <?xml version="1.0" encoding="utf-8"?> <android.support.v4.widget.DrawerLayout xmlns:andr

我已经创建了一个主活动,其中包含一个片段容器,我正在导航菜单选项选择中替换其中的许多片段。工作正常,但问题是:

  • 当我两次单击导航项时,两个相同的片段打开,我必须按两次后退按钮才能返回
  • 当按下back键后所有的片段都被销毁时,我看到一个空页面(我猜这可能是主活动页面)
  • layout\u main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.v4.widget.DrawerLayout 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/main_activity_page"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/pageBackgroundColor"
        tools:context="co.sd.app.MainActivity">
    
        <RelativeLayout
            android:id="@+id/fragment_container"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    
        <android.support.design.widget.NavigationView
            android:id="@+id/side_nav_drawer"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:padding="0sp"
            app:menu="@menu/side_navigation_menu" />
    
    </android.support.v4.widget.DrawerLayout>
    

    请就此向我提出建议。

    这将解决您的第二个问题,当您将片段添加到容器中时,它们将被添加到堆栈中

    if (getSupportFragmentManager().getBackStackEntryCount() == 1) {
                finish();
            }
            else {
                super.onBackPressed();
            }
    
    因此,当堆栈项计数为1时,您必须完成活动


    对于第一个问题,在再次添加相同片段时,必须使用“弹出式堆栈”:
    getSupportFragmentManager().popBackStack()

    太棒了!为我工作,谢谢:)如果有帮助,我很高兴!:)FragmentManager fm=getSupportFragmentManager();fm.popbackbackstack();FragmentTransaction ft=fm.beginTransaction();ft.replace(R.id.fragment_容器、fragment、fragmentTag);ft.commit();在导航菜单中单击同一片段时,使用getSupportFragmentManager().popBackStack();在菜单项的onClick中,它将确保当您尝试再次向堆栈中添加相同的片段时,它将删除现有的片段。Worked:),它维护只终止堆栈中的一个活动,并在BackPress时终止
    if (getSupportFragmentManager().getBackStackEntryCount() == 1) {
                finish();
            }
            else {
                super.onBackPressed();
            }