Search code examples
androidnavigation-drawerandroid-architecture-navigation

Why not working navigating back when I use optionsMenu to navigate a specific Fragment?


I use Navigatation component latest stable version.

I would like to create a shortcut option menu item in my application, which is navigates to a fragment.

This fragment is also used by the drawer menu.

So when I use the drawer menu for navigation, everything is good, but when I navigate to for example Fragment B and after that I use the options menu to navigate to Fragment C, and after the I can not navigate back to Fragment B from drawer, because it always shows Fragment C.

I can solve this problem by adding navController.popBackStack() before the navigation to Fragment C, but this is not good at all, becaouse the previous fragment is destroyed, and I can not go back to it, by pressing back button.

Is there any solution of this problem?

MainActivity
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_main,menu)

        menu?.findItem(R.id.action_worksheet_management)?.setOnMenuItemClickListener {
            val navController = findNavController(R.id.nav_host_fragment_content_main)

            navController.popBackStack()

            navController.navigate(R.id.nav_work)

            return@setOnMenuItemClickListener true
        }

        return true
    }

private fun setUpNavigation() {
        val navController = findNavController(R.id.nav_host_fragment_content_main)
        setSupportActionBar(binding.appBarMain.toolbar)

        val menuItems = mutableListOf(
            R.id.nav_worksheet_browser,
            R.id.nav_product,
            R.id.nav_about,
            R.id.nav_company_info,
            R.id.nav_services,
            R.id.nav_stock_receive,
            R.id.nav_synchronization,
            R.id.nav_order_return,
            R.id.nav_work,
            R.id.nav_settings,
            R.id.nav_certificates
        )

        appBarConfiguration = AppBarConfiguration(
            menuItems.toSet(),
            binding.drawerLayout
        )

        setupActionBarWithNavController(navController, appBarConfiguration)
        binding.navView.setupWithNavController(navController)
    }

  override fun onBackPressed() {
        if (binding.drawerLayout.isDrawerOpen(GravityCompat.START)) {
            binding.drawerLayout.closeDrawer(GravityCompat.START)
        } else {
            super.onBackPressed()
        }
    }

    override fun onSupportNavigateUp(): Boolean {
        val navController = findNavController(R.id.nav_host_fragment_content_main)
        return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
    }

Solution

  • I resolved it, by changed the nav version from 2.4.1 to 2.3.5. I hope it will be fixed later.