在MainActivity上重置addToBackStack()

时间:2016-11-14 14:42:03

标签: android android-fragments fragmenttransaction onbackpressed

我正在使用默认的Navigation Drawer布局和Fragment构建一个Android应用程序,以便从一个布局切换到另一个布局。

布局顺序就像

mapController

Dashboard -> Settings -> Profile Settings 加载MailActivity.class,其中包含main_activity.xml以包含片段

和Dashboard加载ActivityDashboard Fragment。

现在,当我从frameLayout切换到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); } 代码在FragmentTransactionActivityDashboard片段类中从一个片段切换到另一个片段。

问1.如何在加载ActivityDashboard时刷新addBackToStack,以便用户只能选择退出应用程序?

问2.如果布局从导航抽屉更改而不管替换了哪个片段,如何返回ActivityDashboard?

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

ActivityHistory

而不是

ActivityHistory -> ActivityDashboard
MainActivity.class上的

onBackPressed()方法是

ActivityHistory -> ActivitySettings -> ActivityDashboard

1 个答案:

答案 0 :(得分:0)

只需致电

std::remove_cv

在ActivityDashboard