ViewPager with fragments - onPause(), onResume()?

When using ViewPager with fragments, our onPause, onResume methods are not called when moving between tabs. Is there any way we can figure out in the fragment when we're being made visible or being hidden?

Unfortunately I have logic in onResume, onPause, like registering with location services, that never get stopped when switching tabs because onPause never gets called until one exits the whole app.


Solution 1:

The ViewPager comes with the OnPageChangeListener interface. By setting some flags for the previous and currently shown pages, you can emulate this behavior.

Solution 2:

Considering previous solutions are not very clear, here is how I solved it thanks to Phix for his hint:

In the OnPageChange() callback:

    Fragment old_fragment = getActiveFragment(old_position);
    Fragment new_fragment = getActiveFragment(new_position);
    old_f.setUserVisibleHint(false);
    old_f.onPause();
    new_f.setUserVisibleHint(true);
    new_f.onResume();

Then in onResume():

    if (getUserVisibleHint())
        /* resume code */

and in onPause():

    if (!getUserVisibleHint())
        /* pause code */

Here is the getActiveFragment code, avoiding to search for that too:

    return fragmentManager.findFragmentByTag("android:switcher:" + viewPagerId + ":" + position);

NB: Fragment have a isVisible() method, but it doesn't seem to be very consistent, hence the use of UserVisibleHint.

EDIT: Replace the UserVisibleHint by a private flag. Worked much better!

Solution 3:

If you are using Android Support Library (rev 11), you can use getUserVisibleHint or override setUserVisibleHint() to capture the changes visible and hide. Look this post.

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser) {
        // do something when visible.
    }
}