My app has a single Activity with a FragmentPagerAdapter with four fragments (Using the ViewPagerIndicator library). One of these fragments has designs for both a separate portrait and landscape layout, the other three do not and need to be fixed to portrait orientation.
My thought was to set android:configChanges="orientation"
in the manifest and call getActivity().setRequestedScreenOrientation()
in the onResume()
of all the fragments, locking to SCREEN_ORIENTATION_PORTRAIT
in three of them but to SCREEN_ORIENTATION_UNSPECIFIED
in the one that needs to allow rotation, but this doesn't work. The app remains in portrait mode.
Is there a way to achieve this?
It isn't actually necessary for the actual activity to rotate if there is anyway to allow a fragment to change orientation without its activity doing so, but I have not found anything mentioning this being possible. It would also be equally ok if the activity rotates since the tab bar will be hidden when in landscape orientation.
in the fragment you want to set just add to your
onCreate
/onCreateView
in the other fragments you want to allow multi orientation add
Write some code in
AndroidManifest.xml
on the particular activity tag.And Write code in Fragment on
onCreateView
method,for Portrait:
for Landscape:
Issue is if you enable
configChanges
you then need to handleonConfigurationChanged()
method in your activity/fragments.Meaning that if you did fire the
getActivity().setRequestedScreenOrientation()
you would have to manually callsetContentView()
again to reinflate the landscape layout.Also setting `UNSPECIFIED' will not change to landscape, it will just remain where it is.
I would use
getActivity().setRequestedScreenOrientation(SCREEN_ORIENTATION_PORTRAIT)
for the portrait fragments. AndgetActivity().setRequestedScreenOrientation(SCREEN_ORIENTATION_LANDSCAPE)
for the landscape fragments.This will reinflate the activity layout, which means you will then need to keep track of the last ViewPager page you where on, to make sure you show that after the layout has been recreated as to default back to that fragment before they are shown to the user and fragment
onResume()
is called.Its going to be fiddly but, it is possible.
One thing that worked for me was to just put
At the top of the
OnCreateView()
methods for each of the fragments. You would want to replaceActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR
with the appropriateSCREEN_ORIENTATION
constant.Once I did this it worked perfectly on ICS. You don't event have to adjust the manifest for the specific activity.
Override
setUserVisibleHint()
in each fragment.In the portrait only fragments:
in the the portrait/landscape fragment:
This will allow the whole activity to rotate in one fragment, but fix it to portrait in others.