Home > database >  (Kotlin)Fragment Back stack handle
(Kotlin)Fragment Back stack handle

Time:12-22

When I use backStackEntryCount > 1. popbackstack() it is not navigating to any of the fragments of my bottom navigation

What I need to know is, how to stack fragments one time only, so I can press the back button once which will be navigating to the Activity.

 private fun navBottomClick() {
    bottomNavigationView?.setOnItemSelectedListener {

        when (it.itemId) {

            R.id.workout -> {
                var fragmentTransaction: FragmentTransaction =
                    supportFragmentManager.beginTransaction()
                fragmentTransaction.replace(R.id.container, WorkoutFragment(), "WORKOUT")
                fragmentTransaction.addToBackStack("WORKOUT")
                fragmentTransaction.commit()
            }
            R.id.health -> {
                var fragmentTransaction: FragmentTransaction =
                    supportFragmentManager.beginTransaction()
                fragmentTransaction.replace(R.id.container, HealthyFoodFragment(), "HealthFood")
                fragmentTransaction.addToBackStack("HealthFood")
                fragmentTransaction.commit()
            }
        }
        true
    }
}

CodePudding user response:

Try to print log supportFragmentManager.backStackEntryCount.

And my opinion is the condition is supportFragmentManager.backStackEntryCount > 0.

CodePudding user response:

without backStack you can try this

override fun onBackPressed() {
        if (binding.bottomNavigation.selectedItemId == R.id.home) {
            moveTaskToBack(true)
        } else {
            binding.bottomNavigation.selectedItemId = R.id.home
            val homeFragment = HomeFragment.newInstance()
            openFragment(homeFragment)
        }
    }
  • Related