Search code examples
androidandroid-fragmentstabpanel

How to fix Android tab panel in order not to call onCreateView of next tab?


I have an Android application. After I login I have a main activity page which contains 3 tab panels. These 3 panels are fragmented. I have overridden onCreateView for all and I filled onCreateView method in second and third panel and I am calling my service to fill my spinner.

After I login, while I am at the first fragment the onCreateView method of second fragment starts to work and calls the service.

Then when I passed the second tab, third onCreateView of third fragment starts to work and calls the service.

I don't understand this situation.How to overcome this.

Is there a reasonable explanation for this?


Solution

  • It's normal for viewpager load next fragment when you in first fragment.

    You can use fragment below to lazyload:

    public abstract class LazyFragment extends Fragment {
        protected boolean isVisible;
        private boolean loaded = false;
    
        @Override
        public void setUserVisibleHint(boolean isVisibleToUser) {
            super.setUserVisibleHint(isVisibleToUser);
            if(getUserVisibleHint()&&!loaded) {
                loaded = true;
                isVisible = true;
                onVisible();
            } else {
                isVisible = false;
            }
        }
        protected void onVisible(){
            lazyLoad();
        }
        protected abstract void lazyLoad();
    }
    
    public class YourFragment extends LazyFragment{
        public void lazyload(){
           //do thing you want to do when you turn to this page.
        }
    }