Can somebody explain why the onCreate()
and onCreateView()
are being invoked so many times which increments with each orientation change?
Here
I can't point to the documentation which explains this, but the solution is to only create and add the fragment when the activity first loads, like this:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if (savedInstanceState == null) {
Fragment fg = new Right();
getFragmentManager().beginTransaction().add(R.id.right_frag, fg)
.commit();
}
Log.i("Main", "onCreate()");
}
main class should extend FragmentActivity and not Activity.
also look up Activity life cycle on the android doc
Looks like you have so many fragments there! If you define fragment in xml file you can not define "it" again in your code! There are two ways how to define fragmets: dynamiclly (in your code) and statically (in your xml)! Take a look here: http://marakana.com/s/post/1250/android_fragments_tutorial
It is really good tutorial.
An orientation change causes the system to go through the process of saving instance state, pausing, stopping, destroying, and then creating a new instance of the activity with the saved state. So this is the reason why there is so much onCreate and onCreateView calls.
I do not think the if (savedInstanceState == null)
condition in the onCreate
method is a good idea; the state-saving mechanism will not work properly...
If you don't use different layouts for different orientations, I think that you should use android:configChanges="orientation"
in your manifest.
http://developer.android.com/guide/topics/manifest/activity-element.html#config
Yes, this is very bad documented. The explanation is that when the Activity
is restored
it will "auto-magically" restore
the Fragments
that were added in it, so adding
another Fragment
in your Activity
will basically add another new Fragment
on top of the previous Fragment\s
that are actually restored
by Android
.
This behavior is definitely intended, and the approach suggested by @Joris Wit is the correct one.
Also this is very helpful when you think about it, because let's say you have a stack of Fragments
added one on top of each other, and you can navigate back to them using the back
key. In the case of a rotation, if Android
would not restore the backstack of Fragments
you will lose all of them, or you will have to implement some mechanism to keep track of your Fragment
stack
.