v4.app.Fragment When is it created and destroyed?
How exactly does v4.app.Fragment work? I have viewPager with 7 fragments. I’m sure that when moving between fragments, each fragment can be automatically destroyed and created depending on the situation. However, this does not seem to be true.
I decided to try debugging and set some flags for my Fragment class object, like
class MyClass extends Fragment {
public boolean myFlag=false;
When I set ex. to true
somewhere in code that only runs once (e.g. set to true after clicking a button), the value seems to be true until the application ends. Therefore, this indicates that the object has been kept in memory.
However, as the user moves between fragments, it appears that the onCreateView
and onViewStateRestored
methods are called.
Now I’m confused. If fragments are not destroyed, why are these methods executed by Android?
Can I guarantee that my Fragment object will always contain all fields (when the user only moves between Fragments and does not leave the application)?
If not, how can I save and restore its state? The public void onSaveInstanceState(Bundle savedInstanceState)
method seems to run only when the user leaves the application, not when the user moves between fragments.
Have you seen a good tutorial on ViewPager and Fragments?
Solution
And now I feel quite confused. If Fragments are not destroyed, why
those methods are executed by Android?
If you look at this diagram, Fragments
can call onCreateView()
without destroying.
Do I have the guarantee that my Fragment object will be kept always
with all fields (when user only moves beteween Fragments and doesn’t
leave the app)?
It depends on what you’re doing. If you’re dealing with ViewPager, it really comes down to the PagerAdapter
you use and your ViewPager
configuration.
If not how should I save and restore its state? public void
onSaveInstanceState(Bundle savedInstanceState) method seems to be only
run when user left the app, not when user moves between Fragments.
It depends on what conditions you wish to restore the state. For example, for orientation changes, you can call setRetainInstance(true)
on a fragment, and when the configuration changes, the state of the fragment will be preserved given that your fragment
is not in the
background.
Have you seen any good tutorial concerning ViewPager and Fragments?
Android Guide has a good tutorial.