Search code examples
androidandroid-viewpager

How to set screen orientation from code in a viewpager?


So I have an implemented viewpager in my application, and I would like to set the screen orientation PORTRAIT on every page, except one, that should be using BOTH. Now im using this code, but in this case every page using BOTH orientation.

In Mainfest:

<activity android:name=".ViewPagerActivity" android:screenOrientation="portrait">

In the fragment:

getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);

Solution

  • You can use setUserVisibleHint

    in your ViewPager fragments

    From Documentation:

    Set a hint to the system about whether this fragment's UI is currently visible to the user. This hint defaults to true and is persistent across fragment instance state save and restore.

    so in your particular fragment override this method and apply the Orientation change.

    For example:

     @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(isVisibleToUser) {
            Activity activity = getActivity();
            if(activity != null) activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
        }
    }