How to remove up navigation from a specific fragment while using Android Navigation Component Library.
I have recently been using the Android Navigation Library on my personal project. The Project had 3 screens:
- Login fragment
- Home fragment
- Details fragment.
The challenge I encountered was that all my screens had the up navigation icon as shown in the image below.
However, I did not want to have an up navigation icon in the LogIn fragment as it violated the purpose of the up navigation which is to help the user to move up the back stack back to the home screen. So it did not make sense to have Up Navigation here. For the HomeFragment, at no point in time did I ever want the user to move up to the LogIn fragment unless they logged out of the application.
This was the initial code I had in my MainActivity for the NavigationHostFragment:
/**
* Connect the navigation controller to the NavHostFragment
*/
val navHostFragment = supportFragmentManager
.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
val navController = navHostFragment.navController
NavigationUI.setupActionBarWithNavController(this, navController)
To remove the up navigation icon:
- Create an AppBarConfiguration of all the fragments you don't want to contain the up navigation icon. //1
- Pass the appBarConfigurations you have created in the step above to the NavigationController. //2
In my case, I want to remove the up navigation icon from both my Login fragment and Home fragment as shown in the snippet below:
/**
* Connect the navigation controller to the NavHostFragment
*/
//1
val appBarConfiguration = AppBarConfiguration
.Builder(
R.id.BooksFragment,
R.id.logInFragment
)
.build()
val navHostFragment = supportFragmentManager
.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
val navController = navHostFragment.navController
//2
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration)
Once the application is run after making these changes, the screen looked like this:
Happy coding!