1

I'm now working on the Android application which main Activity extends FragmentActivity (support library). This activity contains ViewPager view, which adapter is FragmentStatePagerAdapter. To be exact, the adapter is a custom subclass, which extends FragmentStatePagerAdapter.

Adapter class has getItem() method to return a Fragment instance. I store these fragments within SparseArray not to create new fragment each time getItem() called. When the activity is destroyed, I clear this array, so I hope to create all of these fragments again when activity is recreated.

There is a scenario: user starts the app, then goes to the Android's Home (Launcher) screen, works with another apps, then Android OS kills our application to free up memory. When the user comes back to our application (it is not restarted from the very beginning, but is recreated and resumed from the place user has leaved it on), I watch the following sequence of callback calls:

Application: onCreate() called
Fragment: onAttach() called
Fragment: onCreate() called
Activity: onCreate() called
Fragment: onViewCreated() called
Activity: onStart() called

There are more than one Fragment (ViewPager calls getItem() for the current one and the two its neighbors - next and previous), but let's consider there's only one fragment to simplify it.

I used to think that activity's onCreate() should be called earlier than the fragments ones. This only happens when the app is brought back from background state being previously killed by the OS.

I want to perform some background action before displaying anything within this activity (including fragments, so I don't want their onCreate() methods to be called so early). How may I do this in the described case?

4

1 回答 1

0

我发现最好使用onActivityCreated()回调来确保此时创建主机活动。所以没有必要在 Fragment 的onCreate()方法中对 UI 做一些重要的事情。

于 2013-03-11T13:38:52.887 回答