Search code examples
androidandroid-fragmentsrotation

Turn off auto rotation in fragment


I have a PictureFragment which I use to show a picture in fullscreen when selecting it from my thumbnail. It works fine, but when I rotate my smartphone, the picture also rotates and gets scaled very ugly sothat its height is now its actual width and so on. How can I turn off the rotation for this fragment? I've read always how to do it for a whole activity but for the rest of the activity this runs in I want to keep the auto rotation. Or, if this is also easy possible, how can I manage to scale the picture sensefully on rotation to keep its aspect ratio?


Solution

  • In your Fragment call inside onResume to lock to portrait:

    getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    

    then in onPause to unlock orientation:

    getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
    

    OBS! For the sake, use if(getActivity != null) before using this methods.