1

Without me pasting any code, i have an activity that shows three fragments using a viewpager to swipe between them.

When the activity is created, tab one is showing.. If i select the second tab and go back to the first tab, everything is fine. But if i select the third tab and then select the first tab again, the onResume method is called within the first tab and its causing some undesirable results... why would onResume only be called when coming from the third tab and not the second? Its like tab one is being killed when you swipe to tab three, but tab one is not being killed if you just swipe to tab two..

buradd
  • 1,271
  • 1
  • 13
  • 19
  • Relevant: http://stackoverflow.com/questions/10024739/how-to-determine-when-fragment-becomes-visible-in-viewpager – Daniel Nugent Oct 21 '16 at 23:48
  • 1
    Basically, a ViewPager by default will keep the current Fragment, and one on either side alive (if the current Fragment is one of the ones on either end, then only the one next to it will be kept alive). – Daniel Nugent Oct 21 '16 at 23:50
  • https://developer.android.com/reference/android/support/v4/view/ViewPager.html#setOffscreenPageLimit(int) – Amit Upadhyay Oct 21 '16 at 23:51
  • For the best way to update each Fragment when it becomes visible, see the answer here: http://stackoverflow.com/questions/36503779/refresh-data-in-viewpager-fragment – Daniel Nugent Oct 21 '16 at 23:52

2 Answers2

2

Without seeing the code I can only guess, but when you use tab you are going to be using a FragmentPagerAdapter or FragmentPagerStateAdapter this keeps reference to the fragments that are kept alive. I'm going to guess that you are using the FragmentPagerStateAdapter which only keeps certain fragments alive and destroys other fragments when they leave the view. So that when you are on the 3rd fragment, the first fragment is being destroyed, which is recreated and thus calls onResume when you go back and visit it. When you are on the 2nd tab, the fragment isn't destroyed and so when you visit it, it does not need to call onResume. Fragments keep one fragment to the left and one to the right "alive" even though they are not in view. So when you are on 1, 2 is alive. When you are on 2, 1 & 3 are alive, when you are on 3, 2 is alive. I hope this helps.

BlackHatSamurai
  • 23,275
  • 22
  • 95
  • 156
1

To add more to BlackHat's answer,

You should use FragmentStatePagerAdapter, if you dont already, instead of FragmentPagerAdapter.

Also you should set the OffscreenPageLimit property of yoru view pager to the number of pages that should be retained to either side of the current page in the view hierarchy in an idle state.

Manos
  • 1,471
  • 1
  • 28
  • 45
  • Thank you both blackhat and manos.. settinh the OffscreenPageLimit ultimately did the trick. This was bugging me alot and im very happy to see things working as intended – buradd Oct 22 '16 at 05:50