I have been trying to determine why the onPause()
and the onResume()
methods were not fired when the user switches the the tab to be displayed when using a ViewPager and sectionsPageAdapter.
I assumed that when the user changes the tab being displayed, the onPause()
or the onDestroy()
methods would be called. Then, if the user returns to the tab, the onResume()
method would be called, but it seems it is not the functionality...
is there any way to determine when the user switces a tab and to know to which tab it has been switched? Something like onFragmentBeingDisplayed()
or similar.
Thanks!
EDIT: Answer from Suraj Vaishnav
By editing the constructor from the FragmentPageAdapter
like this super(fm, FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
I could use the desired behaviour on the app
That's because ViewPager loads some fragments on the left side and on the right side of the current fragment. By default, ViewPager loads one on the left side and one on the right side of the fragment. You can change the number via: viewpager.setOfScreenPageLimit(int);
What you thinking is working exactly the same way in androidx's
Fragment. Means onPause
and onResume
will call accordingly. So the first suggestion is to use androix
. Check this answer: https://stackoverflow.com/a/57886441/7682257
For some reason, If you do not want to use androidx
then in your Fragment, override setUserVisibleHint
method, which gives you isVisibleToUser
as a parameter.