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
  • 9,696
  • 3
  • 37
  • 40
Ali
  • 10,396
  • 10
  • 55
  • 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 Iskenderov
  • 8,415
  • 5
  • 60
  • 98
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,099
  • 2
  • 27
  • 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
  • 19,870
  • 7
  • 66
  • 85