سؤال

I have a ViewPager of fragments.
For each fragments, in the onCreateView(), I use AsyncTask to query the server.
I create the fragments in FragmentPagerAdapter's getItem().
However, because getItem() method will be called for the visible fragment and also the adjacent fragments, I am calling the onCreateView() and thus the AsyncTask of the adjacent Fragment even though the fragment is not visible.
How do I only call the AsyncTask of the visible fragment?

Is using onPageSelected() for the ViewPager the correct solution?
I used this method to call AsyncTask instead of in onCreateView() but then the onCreateView() of the fragment is not called.

Thank you.

هل كانت مفيدة؟

المحلول

You could override the method of Fragment:

setUserVisibleHint(boolean isVisibleToUser) {
     super.setUserVisibleHint( isVisibleToUser);
     if(isVisiableToUser) {
     }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top