'why is when fragment is hidden, onStop isn't called?

I attached bottom navigation to my app and call changeFragment. When I call changeFragment, for example, A fragment to B fragment, I expected to be called onStop at A fragment. However, Any lifecycle callback isn't called.. Why is happened?

THIS IS MY CODE..

private fun setBottomNavigation() {
    binding.bottomNavigation.run {
        setOnItemSelectedListener { menu ->
            when (menu.itemId) {
                R.id.navigation_menu_main ->
                    changeFragment(mainFragment, MainFragment.TAG, menu.itemId)
                R.id.navigation_menu_money ->
                    changeFragment(moneyFragment, MoneyFragment.TAG, menu.itemId)
                R.id.navigation_menu_life ->
                    changeFragment(lifeFragment, LifeFragment.TAG, menu.itemId)
                R.id.navigation_menu_food ->
                    changeFragment(foodFragment, FoodFragment.TAG, menu.itemId)
                R.id.navigation_menu_menu ->
                    changeFragment(menuFragment, MenuFragment.TAG, menu.itemId)
                else -> false
            }
        }
        selectedItemId = R.id.navigation_menu_main
    }
}

private fun changeFragment(fragment: Fragment, tag: String, menuId: Int): Boolean {
    supportFragmentManager.commit {
        hide(currentFragment)
        showFragment(fragment, tag)
    }

    currentFragment = fragment
    return true
}

private fun FragmentTransaction.showFragment(fragment: Fragment, tag: String) {
    supportFragmentManager.executePendingTransactions() 
    if (fragment.isAdded) {
        show(fragment)
    } else {
        add(binding.container.id, fragment, tag).show(fragment)
    }
}


Solution 1:[1]

You can use add() and replace() to change fragments in your activity. And the difference between add and replace is that:

add simply add another fragment to the fragment container and does not destroy the existing fragments so they remain active and lifecycle events for those existing fragments are not called.

replace removes the existing fragments to add a new fragment which means lifecycle events like onPause, onStop, and onCreateView will be invoked.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Aung Si Min Htet