Navigation in Bottom Navigaiton View creates/destroys the fragment Navigation 2.4.2

1.9k Views Asked by At

I am using the latest Navigation version 2.4.2.

I set up the bottom nav bar with the Navigation component as follow, the same way recommended by google:

    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    binding = ActivityMainBinding.inflate(layoutInflater)
    setContentView(binding.root)

    val navView: BottomNavigationView = binding.navView

    val navController = findNavController(R.id.nav_host_fragment_activity_main)
    // Passing each menu ID as a set of Ids because each
    // menu should be considered as top level destinations.
    val appBarConfiguration = AppBarConfiguration(
        setOf(
            R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications
        )
    )
    setupActionBarWithNavController(navController, appBarConfiguration)
    navView.setupWithNavController(navController)
}

My menu:

<menu xmlns:android="http://schemas.android.com/apk/res/android">

<item
    android:id="@+id/navigation_home"
    android:icon="@drawable/ic_home_black_24dp"
    android:title="@string/title_home" />

<item
    android:id="@+id/navigation_dashboard"
    android:icon="@drawable/ic_dashboard_black_24dp"
    android:title="@string/title_dashboard"
    xmlns:app="http://schemas.android.com/apk/res-auto" />

<item
    android:id="@+id/navigation_notifications"
    android:icon="@drawable/ic_notifications_black_24dp"
    android:title="@string/title_notifications" />

However, when I navigate from one fragment to the other, its onDestroy() is called and when I navigate back to it is recreated.

This is the case for all the fragment in the BottomNavView except the startDestination. The onCreate() for the startDestination is called only once and when navigating away from it, only the onDestroyView() is called. I want this behavior for all the other fragments as well as I need to put code in the onCreate() method and want it to run once once per lifecycle of the app.

Support for multiple backstack arrive with Navigation 2.4.0 so I don't know what's wrong. when calling findNavController.navigate(...), the previous fragment is kept in the backstack and is not destroyed(), and as far as I know the BottomNavBar calls the same method so I can't figure out why each fragment is being created/destroyed upon each navigation.

Me navigating from : Start Fragment -> Dashboard Fragment -> Navigation Fragment -> Start Fragment

enter image description here

All the fragment except the Start Fragment is recreated.

Any help is appreciated.

1

There are 1 best solutions below

1
Bagadeshkumar R On

For anyone looking for an answer to this question. Google replied that it is expected behaviour.

https://issuetracker.google.com/issues/190893266