Search code examples
androidorientationscreen-size

Android: Restrict activity orientation based on screen size


I have an app that looks good in either orientation on a large or xlarge screen size, but should be restricted to portrait on phones. I know that you can restrict the orientation of an Activity in the manifest, but is there a way to do so conditionally? Or is there some kind of property I can set in the activity itself to choose which orientations are supported?


Solution

  • This is the solution I use in my apps:

    public void onCreate(Bundle savedState) {
        //...
    
        if(isScreenLarge()) {
            // width > height, better to use Landscape
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    }
    
    public boolean isScreenLarge() {
        final int screenSize = getResources().getConfiguration().screenLayout
                & Configuration.SCREENLAYOUT_SIZE_MASK;
        return screenSize == Configuration.SCREENLAYOUT_SIZE_LARGE
                || screenSize == Configuration.SCREENLAYOUT_SIZE_XLARGE;
    }