Prevent Android orientation change on certain devices

android, layout, orientation

Solution

For that, I think you will need to roll up two things in one.

- First, Get device screen size

- And then, based on result, enable or disable orientation.

For the first part:

int screenSize = getResources().getConfiguration().screenLayout &
        Configuration.SCREENLAYOUT_SIZE_MASK;

switch(screenSize) {
    case Configuration.SCREENLAYOUT_SIZE_LARGE:
        Toast.makeText(this, "Large screen",Toast.LENGTH_LONG).show();
        break;
    case Configuration.SCREENLAYOUT_SIZE_NORMAL:
        Toast.makeText(this, "Normal screen",Toast.LENGTH_LONG).show();
        break;
    case Configuration.SCREENLAYOUT_SIZE_SMALL:
        Toast.makeText(this, "Small screen",Toast.LENGTH_LONG).show();
        break;
    default:
        Toast.makeText(this, "Screen size is neither large, normal or small" , Toast.LENGTH_LONG).show();
}

Credit: https://stackoverflow.com/a/11252278/450534 (Solution was readily available on SO)

And finally, based on the result of the above code, either of these:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

OR

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);

Problem

I know you can restrict orientation change in manifest file for your Android application, but I was wondering if there is a way of doing that depending on the device type/size. I would like to prevent it on small/medium phones but allow it on large phones/tablets. What is the best way to achieve that? Any help would be much appreciated.

Original source

Related problems