Question

I'm allowing all possible orientation for my app both for portrait and landscape (small-normal-large-xlarge) but after testing it on a small screen, I just didn't like how it appears so, what I'm trying to do is disable landscape for small layouts. Is there a way to do this ?

All I found was changes to do on manifest file but I believe that by reconfiguring the manifest I will apply the changes to all layouts.

Was it helpful?

Solution

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

OTHER TIPS

Check this link you can check the type of device and set orientation as needed

Android: allow portrait and landscape for tablets, but force portrait on phone?

You can programatically handle runtime configuration changes like that

in your manifest:

    <activity android:name=".MyActivity"
      android:configChanges="orientation|keyboardHidden"
      android:label="@string/app_name">

in your activity

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {

     ///check the screen size and change it to potrait
    }
}

or check this answer to see how to check the screen size and change it

for example 480 screen size devices:Apply in oncreate method:

Display display = getWindowManager().getDefaultDisplay(); 
int width = display.getWidth();
if(width==480){

if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);


}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top