onCreate() and onCreateView() invokes a lot more than required (Fragments)
Solution 1:
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()");
}
Solution 2:
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
.