androidnavigation

Fragments are not adding to navigation stack


I have problem with navigation in application. When click back button in android system, I am going out from APK.I need stacking between startFragment - register/loginFragment and landingFragment - rankingFragment.

Like this I jumping between fragments using navigationBottomBar

 val navHostFragment = supportFragmentManager.findFragmentById(binding.mainFragmentConteinerView.id) as NavHostFragment
    navController = navHostFragment.navController
    NavigationUI.setupWithNavController(binding.mainNavMenu, navController)

I have tried repair it in navigation design tool.


Solution

  • If you're using Android Navigation Jetpack (https://developer.android.com/guide/navigation/migrate), you need to make sure you are using Single Activity Architecture

    (https://medium.com/appcent/a-single-activity-vs-multiple-activities-architecture-96a23b783036)

    This is basically where your app's entire navigation architecture is managed by one activity, hosting a single FragmentContainerView.

    So in your MainActivity's Layout file, have something like this:

    <androidx.fragment.app.FragmentContainerView
          android:id="@+id/core_container"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          app:defaultNavHost="true"
          app:navGraph="@navigation/name_of_nav_graph_for_your_app"
          android:name="androidx.navigation.fragment.NavHostFragment"
    />
    

    Then you need to get the NavController scoped to your MainActivity, which is basically your FragmentContainerView.

    So in your case (inside your MainActivity's OnStart())

    val navController = findNavController(R.id.core_container)
    
    // then to navigate to the next page (from home, to login screen, and to anyother screen, just pass the id of the fragment in your nav graph. In this case we're navigating from the launch screen to the login screen)
    
    navController.navigate(R.id.login_screen_fragment_in_nav_graph, null)
    

    Screens are automatically added into the back stack, so by pressing the back button you will be removing the current page of the stack.