Java – How to disable landscape orientation on small screen layouts

How to disable landscape orientation on small screen layouts… here is a solution to the problem.

How to disable landscape orientation on small screen layouts

I allow my app to have all the possible orientations in portrait-normal-large-xlarge, but after testing on small screens, I just don’t like how it looks like this, and what I want to do is disable the landscape of small layouts. Is there a way to do this ?

All I found was the changes made to the list file, but I believe that by reconfiguring the list, I will apply the changes to all layouts.

Solution

The easiest way to do this is to put it in the method of all activities (better yet, put it in the onCreate() BaseActivity class and extend all 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 whether a device is a phone or a 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;
        }
    }

Related Problems and Solutions