Skip to content Skip to sidebar Skip to footer

Fragment In Tablayout Only Load When User Slide Android

Hi I'm making an app with A fragment and few child fragment inside it using tablayout and viewpager. The problem is all my child fragment (from Tablayout) always execute (load all

Solution 1:

@OverridepublicvoidsetUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
}

you could use above method within your fragment that is within your ViewPagerAdapter

if(isVisibleToUser){//dosomethingwhen the fragment is visible}
else{//dosomethingelse.}

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 ViewPagerAdapter you can do such :

MyFragmentfrag= (MyFragment) pager.getAdapter().instantiateItem(pager, position);

then you could call a method that is within MyFragment

Solution 2:

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

Post a Comment for "Fragment In Tablayout Only Load When User Slide Android"