Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 836
user291701 Avatar asked Jun 01 '12 15:06

user291701


People also ask

How do you make a ViewPager only resume selected fragment?

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.

What is ViewPager?

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.

When should I use ViewPager?

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.

Can we add activity in ViewPager?

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 .


2 Answers

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

like image 123
Phix Avatar answered Oct 02 '22 00:10

Phix


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!

like image 23
3c71 Avatar answered Oct 02 '22 00:10

3c71