5

I am using ViewPager with PagerSlidingTabStrip , i have 3 fragments , every fragment has its own custom listeners. In every fragment I overrided Destroy, Pause methods, but unfortunately when I move from one fragment to other I have to remove listeners of One fragment but none of the above methods are called as fragments remain in memory. These methods are only called when i am moving to another Activity. So can any body tell me how can I know if a fragment is going to made invisible so that I can remove Listeners, otherwise these listeners are going to disturb that data for all my fragments.

NameSpace
  • 10,009
  • 3
  • 39
  • 40
Ali
  • 10,774
  • 10
  • 56
  • 83

3 Answers3

4

I use this in my fragment, this is called twice. 1) when you go out of screen 2) when fragment is first created. TO solve check this link

@Override
    public void setUserVisibleHint(boolean visible){
        super.setUserVisibleHint(visible);
        if (!visible){
            //when fragment becomes invisible to user,do what you want...
        }
}
Community
  • 1
  • 1
Jemshit
  • 9,501
  • 5
  • 69
  • 106
  • setUserVisibleHint method called each time when it is visible to a user. Not only for first time it been created. – Milon Feb 01 '17 at 11:55
  • @DinIslamMilon i didn't say that, read again. This particular code is called twice `if(!visible)`. – Jemshit Feb 01 '17 at 11:58
1

You should be using onPause() and onResume() as onDestroy() only gets called when the fragment is removed from memory, not when it stops being run.

Also, in a paging setup, neighbouring fragments will continue to run. One on either side of current fragment.

For the visibility check you could check this thread:

How to determine when Fragment becomes visible in ViewPager

Community
  • 1
  • 1
Cory Roy
  • 5,379
  • 2
  • 28
  • 47
1

With ViewPager you should better override Fragment.setUserVisibleHint() Fragment.onHiddenChanged() and react on visible/hidden state change. You still need to implement onPause() / onResume(). I explained it in this answer in more details.

Community
  • 1
  • 1
sergej shafarenka
  • 20,071
  • 7
  • 67
  • 86