Hi I\'m making an app with A fragment
and few child fragment
inside it using tablayout
and viewpager
. The problem is all
@Override public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
}
you could use above method within your fragment that is within your ViewPager
Adapter
if(isVisibleToUser){//dosomething when the fragment is visible}
else{//dosomething else.}
be aware to do not initialize views there or anything rather, init your views within onViewCreated
and call the method that you wanna execute on setUserVisibleHint
. another ugly way is to add a scroll listener to your ViewPager
and get the current item position and trigger an action that is within the fragment. to get the fragment from the ViewPager
Adapter
you can do such :
MyFragment frag = (MyFragment) pager.getAdapter().instantiateItem(pager, position);
then you could call a method that is within MyFragment
The Viewpager by default loads the adjacent fragment to ensure make the app smooth, so that when the user swipe to the fragments (already loaded) it is there. To change is default behavior, use
viewpager.setOffscreenPageLimit(int limit)
where limit is how many fragment next to the one you are on will be preloaded.
Hope this helps