I wasted several hours trying to fix this problem so once again i’m paying it forward in the hope it’s helpful to someone else.
The problem is that it’s difficult to control configuration changes in a fragment activity with multiple fragments when you need fragments to behave differently.
Here is my scenario:
I have a fragment activity that displays different fragments one at a time. The first fragment displayed is not allowed to change orientation, it must be locked in portrait.
However the next fragment I show in the same activity needs to be able to change on both portrait and landscape orientations.
Sure I could have just rewritten my code to have the other fragment start in a different activity but that’s besides the point.
Anyway, what you have to do is make sure you can get configuration changes
Manifest code:
Activity code:
// // @Override public void onConfigurationChanged(Configuration newConfig) { if(fragment!=null && fragment.isResumed()){ //do nothing here if we're showing the fragment }else{ setRequestedOrientation(Configuration.ORIENTATION_PORTRAIT); // otherwise lock in portrait } super.onConfigurationChanged(newConfig); }
The code above doesn’t work by itself. You would think so but there’s a problem where you never receive more onConfigurationChanged callbacks after you call setRequestedOrientation.
Luckily we can take advantage of the lifecycle of our fragment to help our activity get out of it’s funk.
When our fragment resumes we can do the following:
Fragment code:
// // @Override public void onResume() { getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR); ..}
I also make sure that my activity goes back to portrait mode if I exit this fragment.
// // @Override public void onPause() { getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); // set the activity back to //whatever it needs to be when going back. super.onPause(); }
This ensures that the activity can go back to being stubborn about orientation changes while letting an individual fragment take over configuration changes while it’s active.
I hope this is helpful! cheers!
6 comments on “How to control orientation changes for fragments in a FragmentActivity with multiple fragments”