Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 414
Zyga Avatar asked Feb 24 '13 14:02

Zyga


People also ask

How do I stop my Android from rotating?

Open your device's Settings app. . Select Accessibility. Select Auto-rotate screen.

How do you prevent data from reloading and resetting when the screen is rotated?

Prevent Activity to recreated Most common solution to dealing with orientation changes by setting the android:configChanges flag on your Activity in AndroidManifest. xml. Using this attribute your Activities won't be recreated and all your views and data will still be there after orientation change.


2 Answers

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);
like image 60
Siddharth Lele Avatar answered Oct 30 '22 02:10

Siddharth Lele


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 
}
like image 32
Swayam Avatar answered Oct 30 '22 02:10

Swayam