Detect ViewPager tab change inside Fragment

AndroidAndroid FragmentsAndroid Viewpager

Android Problem Overview


I have a ViewPager with multiple fragments. In one Fragment I play audio. When I swipe to another fragment I want to stop the audio playback. How do I detect that the another fragment is now visible in the ViewPager?

I've tried overriding onStop and onHiddenChanged. No success. There must be some "you're not active anymore" method to override. No?

Android Solutions


Solution 1 - Android

I did some digging and it turns out that ViewPager will call both: setUserVisibleHint and setMenuVisibility. I would override setUserVisibleHint since the documentation for setUserVisibleHint states:

> Set a hint to the system about whether this fragment's UI is currently visible to the user. This hint defaults to true and is persistent across fragment instance state save and restore. An app may set this to false to indicate that the fragment's UI is scrolled out of visibility or is otherwise not directly visible to the user. This may be used by the system to prioritize operations such as fragment lifecycle updates or loader ordering behavior.

Try putting this code in your fragment:

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
	super.setUserVisibleHint(isVisibleToUser);

	// Make sure that we are currently visible
	if (this.isVisible()) {
		// If we are becoming invisible, then...
		if (!isVisibleToUser) {
			Log.d("MyFragment", "Not visible anymore.  Stopping audio.");
            // TODO stop audio playback
		}
	}
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionl33tView Question on Stackoverflow
Solution 1 - AndroidlouielouieView Answer on Stackoverflow