Some background
The responsibility to keep the state of a fragment throughout the life of the activity is on the FragmentManager
, this is why there is an option to commit
and to commitAllowingStateLoss
when committing a fragment transaction. If left to it's own devices the Fragment
's state will be restored automatically. But... if you add the fragment in code (as opposed to adding it in the xml layout) then it is up to you to add it only when needed.
Usually, in the case of onCreate
it is enough to check that the activity is not being restarted, that is, check that savedInstanceState == null
and only then add the fragment.
Take a look at this snippet from the fragment's guide:
public static class DetailsActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation
== Configuration.ORIENTATION_LANDSCAPE) {
// If the screen is now in landscape mode, we can show the
// dialog in-line with the list so we don't need this activity.
finish();
return;
}
if (savedInstanceState == null) {
// During initial setup, plug in the details fragment.
DetailsFragment details = new DetailsFragment();
details.setArguments(getIntent().getExtras());
getFragmentManager().beginTransaction().add(android.R.id.content, details).commit();
}
}
}
P.S.
The answer to your question:
will there be two different instances in the memory?
Yes, if you just add the fragment on each call to onCreate
there will be more than one instance.