I thought I had understood that you're supposed to call FragmentTransaction.add() in onCreate() and FragmentTransaction.remove() in onDestroy(). My app crashes in onDestroy() with this error:
06-26 15:25:50.213: E/AndroidRuntime(579): java.lang.RuntimeException: Unable to destroy activity {com.myapp/com.myapp.MainActivity}: java.lang.IllegalStateException: Activity has been destroyed
When do I call these things if not in onCreate/onDestroy()?
My problem with that is that when I switch to my horizontal view, and then back to my vertical view, I now have a duplicate layout for at least one of the nested fragments.
My guess is that this is because you are always adding the fragment in onCreate(). Android automatically recreates fragments on configuration changes. Hence, onCreate() should check to see if the fragment already exists before adding it:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getSupportFragmentManager().findFragmentById(android.R.id.content)==null) {
getSupportFragmentManager().beginTransaction()
.add(android.R.id.content,
new RotationFragment()).commit();
}
}
Ok, your solution worked, except instead of using:
if (getSupportFragmentManager().findFragmentById(android.R.id.content)==null)
I used:
if (savedInstanceState==null)
Apparently the fragment manager is not set up by the onCreate function. But, since your answer is mostly correct, I'm marking it as an answer.
I want to thank you again. This is the second time you've been a big help to me, and I really appreciate it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With