Lam
Lam

Reputation: 543

Android Fragment Life Cycle

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?

Upvotes: 3

Views: 2870

Answers (3)

pdegand59
pdegand59

Reputation: 13019

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.

Upvotes: 5

Simon
Simon

Reputation: 11190

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

Upvotes: 0

tyczj
tyczj

Reputation: 73721

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

Upvotes: 1

Related Questions