fakebutt fishmonkey fakebutt fishmonkey - 4 months ago 9
Android Question

Force android app to stay in the orientation it is started in for api level < 18

I am making an app that needs to stay in the orientation it is started in.
I know how to make it always be in portrait or always in landscape but I need it to be able to start in portrait or start in landscape and stay in the same orientation until it's destroyed.

Currently I'm using

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);


in my onCreate() method but it requires API level 18 or higher and I need my app to work on API level 15 or higher. Can you suggest something?

Answer

Here is the example snippet you can use to get the current screen configuration and lock it on all the android devices

It first checks if the screen is in portrait mode if yes then its sets the portrait mode otherwise landscape

if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
        this.setRequestedOrientation(
                ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    } else{

        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }
Comments