简体   繁体   中英

Handling backstack in jetpack navigation

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()

这是我的应用程序的屏幕截图

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM