在 MainActivity 上重置 addToBackStack()

reset addToBackStack() on MainActivity

我正在构建一个 android 应用程序,使用默认的导航抽屉布局和 Fragment 从一种布局切换到另一种布局。

布局顺序如

Dashboard -> Settings -> Profile Settings

MailActivity.class 加载 main_activity.xml 其中包含 frameLayout 包含片段

并且仪表板加载 ActivityDashboard 片段。

现在,当我从 Dashboard 切换到 Settings 然后 Profile Settings 时。 onBackPress 工作正常。但是在 Profile Settings 之后,我从导航抽屉中选择 Dashboard 返回主屏幕。然后按返回键跟随堆栈

Dashboard -> Profile Settings -> Settings -> Dashboard

导航抽屉的代码是

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {

// calling the method displaySelectedScreen()
displaySelectedScreen(item.getItemId());

return true;
}

private void displaySelectedScreen(int itemId) {
// creating Fragment object
Fragment fragment = null;

// initializing fragment
switch (itemId) {
    case R.id.nav_dashboard:
        fragment = new ActivityDashboard();
        break;
    case R.id.nav_calendar:
        fragment = new ActivityCalendar();
        break;
    case R.id.nav_history:
        fragment = new ActivityHistory();
        break;
    case R.id.nav_about:
        fragment = new ActivityAbout();
        break;
    case R.id.nav_settings:
        fragment = new ActivitySettings();
        break;
}

// replacing the fragment
if (fragment != null) {
    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    ft.replace(R.id.content_frame, fragment);
    ft.addToBackStack(null);
    ft.commit();
}

DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}

我在 ActivityDashboardActivitySettings 片段 类.

中使用相同的 FragmentTransaction 代码从一个片段切换到另一个片段

Q 1. 如何在加载 ActivityDashboard 时刷新 addBackToStack,以便用户只有退出应用程序的选项?

Q 2. 当从 Navigation Drawer 更改布局时,无论替换哪个片段,如何返回 ActivityDashboard?

即,当用户在 ActivitySettings 片段上并从导航抽屉更改为 ActivityHistory,然后在 backPress 上,必须跟踪用户

ActivityHistory -> ActivityDashboard

而不是

ActivityHistory -> ActivitySettings -> ActivityDashboard

MainActivity.class 上的 onBackPressed() 方法是

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }

}

只需调用

fragmentManager.popBackStack(stackName /* null if you did not supply a stack name while creating your fragments */, FragmentManager.POP_BACK_STACK_INCLUSIVE);

在您的 ActivityDashboard 中