简体   繁体   中英

Why are the onStart and onResume methods for a Fragment called even though the fragment is not in the foreground

I am using a ViewPager inside a TabLayout . The ViewPager has 3 pages where each page is a fragment. When the activity containing the TabLayout starts, the fragment callback methods upto onResume() are called for fragment1, which is as expected and fragment1 is displayed on the screen.

However, logcat shows that the callback methods upto onResume are also called for fragment2, although fragment2 is currently not being displayed on the screen. This looks odd to me since onResume should only be called when a fragment is about to become visible.

When I select fragment2, onResume is called for fragment3, although fragment3 is not being displayed. So there seems to be a pattern to this behaviour.

What could be the cause for this?

Update: The ViewPager I am using is a subclass of FragmentPagerAdapter .

If is default behavior of ViewPager to call next Fragment when ViewPager is initilized.

You need to use setOffscreenPageLimit()

setOffscreenPageLimit() sets the number of pages that should be retained to either side of the current page

Default value is 1 so next Fragment to the left and to the right will stay in memory.

To prevent from calling next Fragment you need to set 0 value to OffscreenPageLimit

viewPager.setOffscreenPageLimit(0);

on the ViewPager object.

EDIT:

But i have checked by setting limit to 0 .

setOffscreenPageLimit(0) will not work now. when you set limit to 0 you can see below warning in LogCat :

Requested offscreen page limit 0 too small; defaulting to 1

So i advise you to either call setOffscreenPageLimit(2) which will keep all your 3 Fragments in memory otherwise don't call setOffscreenPageLimit(int limit) on ViewPager.

Two things contribute to this behavior:

  1. Fragments are not required to have a UI, in which case it is never "visible" on screen. Basically, if a Fragment is attached to an Activity, its lifecycle methods will be called as appropriate.

  2. ViewPager loads items to either side of the item that is currently displayed. This is in order to have content to show as the user scrolls the page with his finger. By default the off screen page limit is 1, which means that when your first fragment is the current item, the second fragment is loaded off screen in preparation for scrolling.

You can always check which item is displayed by the ViewPager using getCurrentItem() . If you are having problems because the fragment are destroyed and recreated needlessly when they go beyond the off screen page limit, you can increase the page limit with setOffscreenPageLimit() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM