I followed the official documentation to setup a TabLayout with ViewPager2. I used the TabLayoutMediator this way to connect the TabLayout with the ViewPager2:
Your mContext, being exposed by RouteActivity is lingering around even after RouteActivity is destroyed (or recreated). This is happening probably because something is using it. Track what is using mContext and stop that.
I think this is a bug, its listed on google.
https://issuetracker.google.com/issues/151212195 https://issuetracker.google.com/issues/154751401
There is a solution mentioned in the comments that seems to be working for me. Make your FragmentStateAdapter
user the constructor
public FragmentStateAdapter(@NonNull FragmentManager fragmentManager,
@NonNull Lifecycle lifecycle) {
From your container fragment create the adapter as follows:
FragmentManager fm = getChildFragmentManager();
Lifecycle lifecycle = getViewLifecycleOwner().getLifecycle();
fragmentAdapter = new FragmentAdapter(fm, lifecycle);
I had the same similar problem, you need to set the viewPager adapter to null inside onDestroyView , then possible if you are using databinding make sure u set the binding to null. Goodluck
You need to detach and set mediator to null in onDestroyView:
class YourFragment: Fragment() {
private var mediator: TabLayoutMediator? = null
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
mediator = TabLayoutMediator(binding.tabLayout, binding.viewPager) { tab, position ->
tab.setIcon(getTabIcon(position))
tab.text = getTabTitle(position)
}
mediator.attach()
}
override fun onDestroyView() {
super.onDestroyView()
mediator?.detach()
mediator = null
binding.viewpager.adapter = null
_binding = null
}
}