If you are using FragmentStateAdapter
, you should use registerFragmentTransactionCallback
method to check lifecycle of a Fragment's interaction with ViewPager2
.
I need to have back stack of ViewPager2 as i asked here, and implementation is
init {
// Add a FragmentTransactionCallback to handle changing
// the primary navigation fragment
registerFragmentTransactionCallback(object : FragmentTransactionCallback() {
override fun onFragmentMaxLifecyclePreUpdated(
fragment: Fragment,
maxLifecycleState: Lifecycle.State
) = if (maxLifecycleState == Lifecycle.State.RESUMED) {
// This fragment is becoming the active Fragment - set it to
// the primary navigation fragment in the OnPostEventListener
OnPostEventListener {
fragment.parentFragmentManager.commitNow {
setPrimaryNavigationFragment(fragment)
}
}
} else {
super.onFragmentMaxLifecyclePreUpdated(fragment, maxLifecycleState)
}
})
}
My question was to set back stack for fragments of ViewPager2 with each it's own back stack only when they are visible since having OnBackPressed on every fragment caused undesired pop stack, you can modify or use other methods of FragmentTransactionCallback
.
However, i don't know it's false positive or not but Leak Canary shows FragmentMaxLifeCycleEnforcer
instance leaking sometimes, so if you face a problem like this, you might need to unregister FragmentTransactionCallback
in onPause
or other relevant method