5

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.

Zyga
  • 2,367
  • 3
  • 22
  • 32

5 Answers5

6

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

  1. First, Get device screen size
  2. 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);
Community
  • 1
  • 1
Siddharth Lele
  • 27,623
  • 15
  • 98
  • 151
1

Well, I might be wrong, but as far as I know there is no direct way of doing this.

You need to check the screen size programmatically and on the basis of that, allow or disallow orientation changes.

if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE) 
{     
    // screen is large.. allow orientation changes
}

else
{
       //restrict orientation 
}
Swayam
  • 16,294
  • 14
  • 64
  • 102
0

you can use during the activity onCreate check which device size you have and call the method setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); (or whatever orientation you want for that size).

Mind that if the activity is not on the requested orientation, that one will be destroyed a new one created.

Budius
  • 39,391
  • 16
  • 102
  • 144
0

check the screen size in your code and decide to

setRequestedOrientation();

or not

l0v3
  • 963
  • 7
  • 26
0

You need to overwrite the public void onConfigurationChanged(Configuration newConfig) and create your own logic for checking density and screen size.

But beware.. it's not good practice.

Wiebe Elsinga
  • 386
  • 3
  • 15