androidandroid-fragmentsandroid-viewpagerandroid-fragmentactivityfragmentstatepageradapter

setUserVisibleHint() issue with FragmentStatePagerAdapter


I know this question has already been asked on different website (such as here and there for example, but I struggle to find a solution to my specific use case.

Here is the thing: I have 3 tabs (each tabs extends Fragment) which are hosted by an ActionBarActivity (called Home). Home holds a ViewPager which extends a FragmentStatePagerAdapter (this is where the differents tabs are created).

When I swipe to the last tabs (the 3rd one), I use setUserVisibleHint() to load some data from server using AsyncTask<>:

public class TabOperations extends Fragment {

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(isVisible())
            loadUserRequestByDate(); // Launch Asynctask<> method.
    }
}

It works well when a swipe from first tab to the last one. But, When I swipe back to the tab before (so, the 2nd one), the method in setUserVisibleHint() (so, loadUserRequestByDate()) is triggered.

How can I avoid this behaviour?


Solution

  • Have you tried retaining the fragments with setOffscreenPageLimit(3) for your viewpager.

    http://developer.android.com/reference/android/support/v4/view/ViewPager.html#setOffscreenPageLimit(int)