Search code examples
androidbottomnavigationviewandroid-bottomnav

How can I show a fragment using a BottomNavigationView with valid back stack?


Edit:

The original question was Is there a way to get a reference to a fragment that is displayed using a BottomNavigationView?. But I've figured some things out and realized I was asking the wrong question.

I'd like to get a reference to a fragment that is being displayed using a BottomNavigationView.

This is how my BottomNavigationView is being setup. It's in onCreate of an Activity.

val navView: BottomNavigationView = findViewById(R.id.nav_view)
val navController = findNavController(R.id.bottom_nav_view_nav_host)
    
val appBarConfiguration = AppBarConfiguration(setOf(
    R.id.navigation_first_list,
    R.id.navigation_second
))

setupActionBarWithNavController(navController, appBarConfiguration)
    bottomNav.setupWithNavController(navController)

I've tried to get the fragment with bottomNav.findFragment<TheFragmentType>() it throws an exception.


Solution

  • I was asking the wrong question originally. I can just use the navController to call the correct navigation component in order to show the right fragment with a back stack.

    val bundle = bundleOf("someId" to "theId")
    navController.navigate(R.id.action_navigation_list_to_details, bundle)