onCreateView of second fragment (tab) is called while on the first

偶尔善良 提交于 2019-12-06 19:23:24

You must know how the viewPager works populating the fragment in the different positions

When you start on the position 0, then the fragment on the position 0 and the one of the position 1 are created.

Then when you swipe to the position 1 the fragment on the 2 position is created, so you have now the three fragments created on the different positions (0,1,2..assuming you have only 3 pages on the viewPager).

We swipe to the position 2, the last one, and the fragment on the first position (0) get destroy, so we have now the fragments on the positions 2 and 3.

This is how Fragment LifeCycle Works

you can set mViewPager.setOffscreenPageLimit(2); // 2 is just an example to limit it

If you want some code to execute when Fragment become Visible to User add part of code in setUserVisibleHint method

By default it is viewpager.setOffscreenPageLimit(1) , meaning View pager will by default load atleast 1 on the right and one on the left tab of current tab.

It is done so, mostly because there is a point when you slide viewpager, when certain area of both tabs is visible. For those smooth transitions preloading is required.

You cannot set it viewpager.setOffscreenPageLimit(0).

The only way out is to use this method setUserVisibleHint add this to your fragment

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser) {
        // load data here
    }else{
       // fragment is no longer visible
    }
}

This will be called only when that particular tab is visible to user, so only then you can call all loading function.

check sample example

Put your AsyncTask method inside this.

You can override setMenuVisibility like this:

@Override
public void setMenuVisibility(final boolean visible) {
   if (visible) {
      //execute AsyncTask method
   }

   super.setMenuVisibility(visible);
}

Happy coding!!

Override below method and move your code for Aync task into this instead of onStart() or onCreateView.

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser) {
        // Load your data here or do network operations here
        isFragmentLoaded = true;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!