0

I have a bottom navigation bar which is connected with navHost and is configured using the following code:

    Val navHostFragment =supportFragmentManager.findFragmentById(R.id.fragment) as NavHostFragment
    val navController = navHostFragment.navController

    val bottomNavBar = findViewById<BottomNavigationView>(R.id.bottomBar)
    setupWithNavController(bottomNavBar, navController)

I have 4 fragments now when I switch to 2nd fragment(by clicking on 2nd icon in the bottom navigation bar) and then I navigate to another fragment which is linked to the 2nd fragment. When I click on the back button I switch to 2nd fragment.

All good till far.

The problem is: I want to go back to 2nd fragment from the opened fragment when I reselect the same icon in the bottom navigation bar

1 Answers1

0

I solved my issue with the help of this thread. If someone is facing the same issue, check this out:

Android clear backstack after reselecting Bottom Navigation tab

I have integrated a better solution which lets you have animations too when switching from one fragment to another.

val id = navController.currentDestination?.id
        when (id) {
            R.id.detailedTransactionAnalysis -> {
                navController.navigate(R.id.action_detailedTransactionAnalysis_to_MainScreen)
            }
            R.id.detailedCategoryTransactionsFragment -> {
                navController.navigate(R.id.action_detailedCategoryTransactionsFragment_to_MainScreen)
            }
            R.id.addTransaction -> {
                navController.navigate(R.id.action_addTransaction_to_Stats)
            }
        }
        navController.popBackStack(reselectedDestinationId, inclusive = false)

It works totally fine.