Handling backstack in jetpack navigation

310 views Asked by At

I am using BottomNavigationView with Jetpack Navigation. I have also set all Fragments as top level destination.

val host : NavHostFragment = supportFragmentManager
            .findFragmentById(R.id.nav_host_fragment) as NavHostFragment? ?: return
        val navController = host.navController
        val appBarConfig = AppBarConfiguration(topLevelDestinationIds = setOf(R.id.library_fragment,R.id.account_fragment,R.id.calender_fragment,R.id.home_fragment,R.id.notice_fragment))
        val bottomNavView = binding.bottomNavView

        setSupportActionBar(binding.toolbar)
        setupActionBarWithNavController(navController,appBarConfig)
        bottomNavView.setupWithNavController(navController)

On second bottom navigation menu item there is LibraryFragment in which I am using TabLayout. There is LibraryFoldersFragment corresponding to a Tab inside of LibraryFragment. LibraryFoldersFragment contains a RecyclerView. On clicking RecyclerView item, LibraryFilesFragment will replace LibraryFoldersFragment.

val fragment = LibraryFilesFragment.newInstance(item)
                childFragmentManager.beginTransaction().addToBackStack(null).replace(R.id.frameLayout, fragment)
                    .commit()

Here is the Screenshot of my app

The problem is that on pressing back button in LibraryFilesFragment app is navigated directly to first bottom navigation menu item. But I want it to navigate to LibraryFoldersFragment.

1

There are 1 answers

2
333 On

Since you are using Navigation component from Jetpack, instead of committing a fragment transaction by yourself. Create a navigation xml for declaring your LibraryFoldersFragment to LibraryFilesFragment navigation. Use findNavController().navigate() on recyclerView Item click to navigate. Setup bottomNavView with NavController with GraphIds of different desired nav xml created.

Sample reference