片段 backStackEntryCount 总是 returns 0

Fragment backStackEntryCount always returns 0

我在 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()
    }
}

我想根据 backStackEntryCount 设置后退按钮的可见性,但它总是返回 0。我做错了什么吗?

在条目计数检查之前添加fm.executePendingTransactions()

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