Reputation:
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?
Upvotes: 22
Views: 9214
Reputation: 13
@SuppressLint("SourceLockedOrientationActivity")
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
activity?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
//Rest of the code
}
override fun onDestroyView() {
super.onDestroyView()
activity?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
}
Without overriding onDestroyView()
all your fragments of activity will have locked orientation that you defined in one of your fragments this way
activity?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
Upvotes: 0
Reputation: 727
Simple solution using Googles Navigation Conponents:
In your Activity:
navController.addOnDestinationChangedListener { _, destination, _ ->
if (destination.id == R.id.fragmentB) {
requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
} else if (requestedOrientation != ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR) {
requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR
}
}
This logic would lock the screen orientation of "fragmentB" (Id resource from your navigation graph) to portrait.
navController
is an instance of androidx.navigation.NavController
Upvotes: 3
Reputation: 325
Add in manifest
android:configChanges="keyboardHidden|orientation"
add in 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);
}
}
}
Upvotes: 0
Reputation: 22064
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.
Upvotes: 41