Have one activity app, where I have HomeFragment from which I open HostFragment, and HostFragment has ViewPager2 with 3 fragment items TabFragment1, TabFragment2 and TabFragment3.
When I open the HostFragment, and then go back, my tabFragments' instances are not removed. Below is the logs from lifecycles
navController.navigate(directionToHostFragment)
- HostFragment OnStart HostFragment{c37542c}
- TabFragment1 OnStart TabFragment1 {f41b08}
navController.popBackStack()
- HostFragment OnPause HostFragment{c37542c}
- HostFragment OnStop{c37542c}
- HostFragment OnDestroy {c37542c}
navController.navigate(directionToHostFragment) Blockquote
- HostFragment OnStart{2670c03}
- TabFragment1 OnStart{f45b87d}
navController.popBackStack()
- HostFragment OnPause{2670c03}
- HostFragment OnStop{2670c03}
- HostFragment onDestroy{2670c03}
From ids you can see that there is a new TabFragment1 instance and old one haven't destroyed(I have logs in onPause(), onStop() etc.).
Some code snippets: Adapter for viewPager2 I used -
class LessonTabsAdapter(fragmentActivity: FragmentActivity, val pages: List<BaseFragment>) :
FragmentStateAdapter(fragmentActivity) {
override fun getItemCount() = pages.size
override fun createFragment(position: Int) = pages[position]
}
Some part from TabFragment1
class TabFragment1 : BaseFragment(R.layout.fragment_tab_1) {
private var mediaPlayer: MediaPlayerClass? = null
private lateinit var player: SimpleExoPlayer
private val viewModel by sharedViewModel<SomeViewModel>()
private val binding by viewDataBinding(FragmentTab1Binding::bind)
//Overriden onViewCreated(..) and some private methods
}
So any hints how to deal with this problem?
When you open the HostFragment the
ViewPager2creates a fragment in the lifecycle provided. In this case you are passing activity as the parameter so, it is creating the fragments inActivity'slifecycle. You can check the same by printing the activity?.supportFragmentManager?.fragments list. If you want to couple theViewPager2's childs withHostFRagment, you need to pass the fragments instance to theFragmentStateAdapter. Check the function2that I have added. The best way to implement theViewPager2is by using function3.