Search code examples
androidandroid-fragmentsandroid-activityandroid-tablayout

How to stop the rotation of an activity only for a specific fragment in TabLayout?


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!


Solution

  • 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()