Zyga
Zyga

Reputation: 2427

Prevent Android orientation change on certain devices

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.

Upvotes: 5

Views: 787

Answers (5)

Swayam
Swayam

Reputation: 16364

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 
}

Upvotes: 1

Wiebe Elsinga
Wiebe Elsinga

Reputation: 406

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.

Upvotes: 0

Siddharth Lele
Siddharth Lele

Reputation: 27748

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);

Upvotes: 6

l0v3
l0v3

Reputation: 973

check the screen size in your code and decide to

setRequestedOrientation();

or not

Upvotes: 0

Budius
Budius

Reputation: 39846

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.

Upvotes: 0

Related Questions