Home > Enterprise >  Back button for single activity with multiple fragments
Back button for single activity with multiple fragments

Time:04-01

With jetpack navigation, single activity with multiple fragments. For example, there is only one activity with 3 fragments.

  • MainActivity
  • FragmentMain
  • FragmentA
  • FragmentB

FragmentMain is the main fragment in the MainActivity, while on FragmentMain, the top left corner is a hamburger menu icon, which will open the navigation drawer menu.

After it navigates to FragmentA or FragmentB via the actions, the hamburger menu icon stays the same with the same behavior that it opens the navigation drawer when clicked.

How to change this hamburger menu icon to a back button icon? when clicked, it should go back to the main fragment.

Creating a new project in Android Studio and choose Navigation Drawer Activity as the template will set up the single activity with 3 fragments described above.

CodePudding user response:

Just add this in your root activity.

if (supportFragmentManager.backStackEntryCount > 0) {
  supportActionBar!!.setDisplayHomeAsUpEnabled(true)
  toolbar.setNavigationOnClickListener {
      if (supportFragmentManager.backStackEntryCount > 0) {
          super.onBackPressed()
      } else {
          supportActionBar!!.setDisplayHomeAsUpEnabled(false)
          drawerLayout.addDrawerListener(toggle)
          toggle.syncState()
          drawerLayout.openDrawer(GravityCompat.START)
      }
  }
} else {
  supportActionBar!!.setDisplayHomeAsUpEnabled(false)
  drawerLayout.addDrawerListener(toggle)
  toggle.syncState()
}

CodePudding user response:

Try this in your activity

NavigationView nav_view = (NavigationView) findViewById(R.id.nav_view);
          drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment);

        appBarConfiguration =
                new AppBarConfiguration.Builder(navController.getGraph()).build();
        setupActionBarWithNavController(this, navController,appBarConfiguration);
        NavigationUI.setupWithNavController(nav_view, navController);
        NavigationUI.setupActionBarWithNavController(this, navController);
        NavigationUI.setupActionBarWithNavController(this, navController, drawer);
  • Related