I have a action bar with 3 navigation tabs: Fragment 1, Fragment 2 and Fragment 3. Now, I want to do a task whenever Fragment 3 selected, so I put my task code in onCreateView() method. However, I find that Fragment 3 does not do the task, it means the onCreateView() method is not called. (I check this by logging). The other strange things is: - When I slide: F2-> F3: the task not work. - When I slide: F1->F2->F3: the task work. (onCreateView() method called) I don't know why F3's onCreateView() method called when I slide from F1 to F3? Any ideas for this?
3 Answers
The remark from tyczj is correct but it does not give a solution to the problem.
In your F3, just override setUserVisibleHint(boolean) and when boolean is true, it means that F3 is now visible inside the ViewPager
.
Note that you can rely on this method because you are using a ViewPager and it properly set the user visible hint when a fragment is shown.
When you are not using ViewPager, you can't rely on this method unless you are explicitly calling the method when you know that the fragment is visible.
EDIT : setUserVisibleHint()
is not called by the ViewPager, but by the FragmentPagerAdapter.

- 12,776
- 8
- 51
- 58
-
Does the system call setUserVisibleHint() method or onCreateView() first? If I know this, I can put my code into the correct method. – Hoang Lam Jun 07 '14 at 07:33
-
If you are using a ViewPager, onCreateView() will be called first, when the fragment will get created. Like tyczj said, a fragment can be created even though it's not visible, to ensure a smooth scrolling. Then setUserVisibleHint() will be called when a fragment will get scrolled in. This method is called by the ViewPager and not directly by the system. – pdegand59 Jun 07 '14 at 10:12
-
1Just a note, setUserVisibleHint() is actually called by the FragmentPagerAdapter. http://grepcode.com/file/repo1.maven.org/maven2/com.google.android/support-v4/r7/android/support/v4/app/FragmentPagerAdapter.java?av=f#128 – pdegand59 Jun 07 '14 at 10:17
Because a ViewPager
loads the next view so that it is ready when you want to scroll to the next fragment. by default the viewpager loads the previous current and next fragment in the ViewPager so when you scroll from F1 to F2, F3 is going to be loaded in so that you have a smooth scroll when you go to F3

- 71,600
- 54
- 194
- 296
The previous answer tells you why what you are doing won't work. But to correct it you will want to create a AsyncTaskLoader and use the fragments LoaderManager to load and manage the task. See http://developer.android.com/guide/components/loaders.html

- 10,932
- 50
- 49