1

I have 10 tabs in my activity. As soon as I open the activity the first fragment gets displayed but the method (AsyncTask) present in the next fragment gets called. And if I go to the next tab say 3rd tab then the method present in the 4th fragment gets called and so on.

I don't understand this behavior. Please help!

Amit Vaghela
  • 22,772
  • 22
  • 86
  • 142
Vaibhav Dhunde
  • 369
  • 1
  • 4
  • 15

4 Answers4

3

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

Dipali Shah
  • 3,742
  • 32
  • 47
3

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

Amit Vaghela
  • 22,772
  • 22
  • 86
  • 142
2

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!!

Hemant Parmar
  • 3,924
  • 7
  • 25
  • 49
1
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;
    }
}
Rajdeep
  • 270
  • 2
  • 11