I’m using Android support library v13. There is a strange thing I couldn’t understand.
When creating new activity, I load fragment as:
Main activity layout:
...
<FrameLayout
android:id="@+id/fragment_1"
... />
In onCreate() of main activity:
mFragment = (FragmentActivity) getSupportFragmentManager().findFragmentById(R.id.fragment_1);
// if screen orientation changed, no need to create new instance of fragment
if (mFragment == null) {
mFragment = ...; // create new instance of fragment
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.fragment_1, mFragment);
// because this is called ONCE, we can use this method
ft.commitAllowingStateLoss();
}
Now, everything works perfectly in emulators 1.5, 1.6 and 2.2. I have a phone 2.2.2.
But there is an exception: if the app is running, and screen orientation changed. Inside onActivityCreated(), getActivity() sometimes returns null. This only happens in emulators 1.5/ 1.6/ 2.2.
My phone 2.2.2 works very well, I test hundreds of times but never catch that bug. Even other emulators 3.x, 4.x work well too. Unfortunately I don’t have phone 1.5/ 1.6/ 2.2.
So did you have experience with this? Is that a bug of the support library, or emulators?
Changing Android device orientation recalls your
onCreatemethod, I believe. As a result, weird things tend to happen. There are two things that you could potentially do:1- You can try catching the orientation change and doing some code there to try to prevent the issues that result from orientation changing:
2- Or prevent orientation-changing altogether in your manifest by adding:
android:screenOrientation="portrait"to your main activity tag, to stop this issue from reoccuring.. that is, if you are willing to prevent orientation changing.
I generally use option 2 for my apps because orientation changing tends to cause all sorts of problems.
Side note: I’ve seen people say they add
android:configChanges="orientation|keyboardHidden"to their main activity’s manifest to fix some orientation troubles as well, so that may be worth a try as well.