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.
1 Answer. Show activity on this post. You cannot do that, the viewpager requires at least one fragment to the left and one to the right. I suggest you move the onResume() logic to a separate method and call it when the fragment becomes visible.
Layout manager that allows the user to flip left and right through pages of data. You supply an implementation of a PagerAdapter to generate the pages that the view shows. ViewPager is most often used in conjunction with android.
ViewPager in Android allows the user to flip left and right through pages of data. In our android ViewPager application we'll implement a ViewPager that swipes through three views with different images and texts.
You can't use ViewPager to swipe between Activities . You need to convert each of you five Activities into Fragments , then combine everything in one FragmentActivity with the Adapter you use with ViewPager .
The ViewPager comes with the OnPageChangeListener
interface. By setting some flags for the previous and currently shown pages, you can emulate this behavior.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With