Reputation: 2119
"If an activity is paused or stopped, the system can drop the activity from memory by either asking it to finish, or simply killing its process.". When the user goes back to the activity, it restores it's state with a bundle.
My question is:
is it important to do this in oncreate:
if(savedinstance != null)
{
fragement = fm.findFragmentByTag("tag");
}
else
{
fragment = new Fragment();
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.webViewFrame,fragment,"tag");
ft.commit()
}
instead of just this:
fragment = new Fragment();
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.webViewFrame,fragment,"tag");
ft.commit()
Upvotes: 3
Views: 2846
Reputation: 38309
If you are correctly saving the state of your activity and fragment in onSaveInstanceState()
, and you want your activity to be recreated in the state it had before it was killed, you should use the first block of code you posted.
The FragmentManager
saves its state, and when recreated, restores the fragments it was holding when the activity was killed. It steps them through the build-up lifecycle events using the fragment's saved state: create, createView, start, resume.
I'm pretty sure if you try running the second block of code, you will find after restart that you have two instances of your fragment in the FragmentManager
--the one added when the activity was first create, and the one added after restart.
For this all to work correctly, you must carefully save the state of both your activity and fragment(s) in the onSaveInstanceState()
method of each, and then in onCreate()
test savedInstanceState
and when not null, use the bundle to restore the state of your activity/fragment.
This is the guide for saving/restoring activity state. More info here.
Upvotes: 5