Search code examples
javaandroidlayoutlandscape

How to disable landscape on small screens layout


I'm allowing all possible orientation for my app both for portrait and landscape (small-normal-large-xlarge) but after testing it on a small screen, I just didn't like how it appears so, what I'm trying to do is disable landscape for small layouts. Is there a way to do this ?

All I found was changes to do on manifest file but I believe that by reconfiguring the manifest I will apply the changes to all layouts.


Solution

  • The easiest way is to put this in the onCreate() method of all your Activities (better yet, put it in a BaseActivity class and extend all your Activities from it)

    @Override
    protected void onCreate(Bundle bundle) {
       super.onCreate(bundle);
    
       if (isLargeDevice(getBaseContext())) {
            this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
       } else {
            this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
       }
    }
    

    You can use this method to detect if the device is a phone or tablet:

    private boolean isLargeDevice(Context context) {
            int screenLayout = context.getResources().getConfiguration().screenLayout;
            screenLayout &= Configuration.SCREENLAYOUT_SIZE_MASK;
    
            switch (screenLayout) {
            case Configuration.SCREENLAYOUT_SIZE_SMALL:
            case Configuration.SCREENLAYOUT_SIZE_NORMAL:
                return false;
            case Configuration.SCREENLAYOUT_SIZE_LARGE:
            case Configuration.SCREENLAYOUT_SIZE_XLARGE:
                return true;
            default:
                return false;
            }
        }