Reputation: 161
I have an activity in which I have added a TabLayout
. Each tab contains a fragment. I want to block the rotation only in a single fragment, not in all. This is the code that I'm using in a single fragment:
@Override
public void onResume() {
super.onResume();
if (activity != null) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
@Override
public void onPause() {
super.onPause();
if (activity != null) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
But it stops the rotation in every fragment. How to solve this? Thanks!
Upvotes: 0
Views: 106
Reputation: 465
You could try to override setUserVisibleHint(boolean isVisibleToUser)
in the Fragment to know when the fragment is actually shown, eg. :
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if(isVisibleToUser && null != activity) {
activity.setRequestedOrientation(
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
else if(!isVisibleToUser && null != activity) {
activity.setRequestedOrientation(
ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}
}
https://developer.android.com/reference/android/app/Fragment.html#setUserVisibleHint
Or put it elsewhere than onResume()/onPause()
and where the activity will not be null, eg. onAttach()
Upvotes: 2
Reputation: 5351
Change your onPause
method to allow every orientation in your activities using SCREEN_ORIENTATION_UNSPECIFIED:
@Override
public void onPause() {
super.onPause();
if (activity != null) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}
}
hope this helps!
A bit deeper:
You don't have to specify nothing in your activity, but just work with fragment.
In your fragment use onResume and onPause methods like follows:
@Override
public void onResume() {
super.onResume();
if (activity != null) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
@Override
public void onPause() {
super.onPause();
if (activity != null) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}
}
and it should work
Upvotes: 1