Search code examples
androidandroid-fragmentsandroid-orientation

How to change orientation to Landscape in a fragment, but read from sensor when back to activity?


I start a fragment from activity, and this is when I want the orientation to change to landascape, but as soon as the app is back to the activity, I want the orientation to be dependent on the sensor. So far, I do it this way in my fragment:

getActivity().setRequestedOrientation(
                ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

But when I go back to the activity, the screen is still in landscape, but instead, when I'm back to the activity, I want the the screen orientation to be dependent on the sensor.


Solution

  • What you are actually doing in the fragment is setting the orientation of the Activity containing it. getActivity().... So what you need to do is reset the orientation of the activity once the fragment is detached from the activity. You can, for example, override the onDetach() for your fragment and call the:

    getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
    

    there. Or you could try to override the various methods within your fragment and see which works best for you.