8

When dealing with login screens, I am trying to work out the better approach - either execute navigation "action" to go to login fragment on first use (and hide back button to actual app), or start a new login activity (with its own nav graph). For the first approach (just using navigation components), I do not know the way to remove the back button without a hack "hide". I tried using navoptions, setpopupto etc., but it does not work. Code below:

val navOptions = NavOptions.Builder()
                .setPopUpTo(R.id.home_fragment, true)
                .build()

host?.navController?.navigate(R.id.action_global_signUpFragment_dest, null, navOptions)

Two questions then: 1) How to properly handle login transition with just navigation component? 2) Is starting a new login activity, with separate nav graph, a better idea?

Rowan Gontier
  • 821
  • 9
  • 14

2 Answers2

11

I think the first approach is better. To hide the 'back' button on your toolbar inside signUpFragment you can use AppBarConfiguration, and customize which destinations are considered top-level destinations. For example:

val appBarConfiguration = AppBarConfiguration.Builder(setOf(R.id.home_fragment, R.id.signUpFragment_dest)).build()
NavigationUI.setupWithNavController(toolbar, navController, appBarConfiguration)

This way home_fragment and signUpFragment_dest will be considered top-level destinations, and won't have back button on toolbar.

Alex
  • 9,102
  • 3
  • 31
  • 35
  • If the main app has a bottom navigation bar, and the login section does not, you think I should just set bottom nav visibility in fragments - ie a good practice? That is one reason a separate login activity is on my mind. – Rowan Gontier Nov 29 '18 at 23:49
  • @RowanGontier for hiding the bottom navigation bar you can attach NavigatedListener to your NavController inside activity, and based on your current destination hide/show the bottom navigation bar. – Alex Nov 30 '18 at 08:05
  • 3
    Great, it works. navController.addOnNavigatedListener { navController: NavController, navDestination: NavDestination -> when (navDestination.label) { getString(R.string.fragment_sign_up) -> { bottom_navigation.visibility = View.GONE } getString(R.string.fragment_explore_promos) -> { bottom_navigation.visibility = View.VISIBLE } } } – Rowan Gontier Dec 02 '18 at 22:25
0

Another option for solving the back button problem is how I did it here. Also, rather than show/hide the bottom nav bar, I have two NavHostFragment, one main full screen one, and one contained within the home fragment (above the bottom nav bar).

When I want to navigate to a full screen view I call this extension function,

fun Fragment.findMainNavController(): NavController =
    Navigation.findNavController(activity!!, R.id.nav_host_fragment)

then navigate via the main graph.

This makes sense conceptually to me, to have parent and child nav graphs.

Carson Holzheimer
  • 2,890
  • 25
  • 36