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.
Asked
Active
Viewed 3,110 times
3 Answers
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...
}
}
-
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:
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