Home > other >  Fragment backStackEntryCount always returns 0
Fragment backStackEntryCount always returns 0

Time:05-20

Code I am using in the Activity:

private fun addFragmentToActivity(fragment: Fragment?) {
    if (fragment == null) return
    val ft = supportFragmentManager.beginTransaction()
    ft.replace(R.id.container, fragment)
    ft.addToBackStack(null)
    ft.commit()
    checkForBackStack()
}

private fun checkForBackStack() {
    val fm = supportFragmentManager
    if (fm.backStackEntryCount > 0) {
        binding.backIV.visible()
    } else {
        binding.backIV.gone()
    }
}

I want to set visibility of back button based on backStackEntryCount, but it is always returning 0. Is there anything wrong I am doing?

CodePudding user response:

Add fm.executePendingTransactions() before entries count check:

private fun addFragmentToActivity(fragment: Fragment?) {
    if (fragment == null) return
    val ft = supportFragmentManager.beginTransaction()
    ft.replace(R.id.container, fragment)
    ft.addToBackStack(null)
    ft.commit()
    fm.executePendingTransactions()
    checkForBackStack()
}
  • Related