If you show/hide fragment (such as using BottomNavigationView), you can listen to Fragment.onHiddenChanged.
class TestFragment : Fragment() { override fun onHiddenChanged(hidden: Boolean) { super.onHiddenChanged(hidden) Timber.d("isVisible=${!hidden}") }}
onHiddenChanged
will not be called the first time the fragment is shown
Called when the hidden state (as returned by isHidden() of the fragment has changed. Fragments start out not hidden; this will be called whenever the fragment changes state from that.
To make sure onHiddenChanged
is called during the first time, you can hide and show the fragment when first added.
if (!fragment.isAdded) { transaction.add(R.id.fragmentContainer, fragment, tag) transaction.hide(fragment) transaction.show(fragment)}else { transaction.show(fragment)}