Search code examples
androiddynamicandroid-studioandroid-orientation

Android: Prevent Orientation to change programmatically


I'm using:

setRequestedOrientation(getResources().getConfiguration().orientation);

and later on:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);

it prevents the orientation to change until a task is finished, but it only works on portrait, when app is on landscape it doesn't stop orientation to change.

Any suggestions?
Oim~


Solution

  • I got it to work properly in all cases now.

    To fix the screen:

    if (getWindowManager().getDefaultDisplay().getRotation()== Surface.ROTATION_0)
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    if (getWindowManager().getDefaultDisplay().getRotation()== Surface.ROTATION_90)
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    if (getWindowManager().getDefaultDisplay().getRotation()== Surface.ROTATION_270)
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
    

    and then to allow rotations again:

    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
    

    Oim~