Disable auto-rotation in fragment

I have a PictureFragment that I use to show an image in full screen when I select it from my sketch. It works fine, but when I rotate my smartphone, the image also rotates and scales very ugly, so its height is now equal to its actual width and so on. How can I turn off rotation for this fragment? I always read how to do this for all the activities, but for the rest of this work I want to keep the auto-rotation. Or, if it is also easily possible, how can I intelligently scale the image while rotating to maintain its aspect ratio?

+11
source share
2 answers

In his Fragment call inside onResume to lock the portrait:

 getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); 

then in onPause to unlock the orientation:

 getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR); 

OBS! To do this, use if(getActivity != null) before using these methods.

+25
source

Add to manifest

android: configChanges = "keyboardHidden | orientation"

add to your fragment

 @Override public void onConfigurationChanged(@NonNull Configuration newConfig) { super.onConfigurationChanged(newConfig); if (getActivity() != null) { if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) { getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } else if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) { getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } } } 
0
source

All Articles