Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamarin Android lock orientation to portrait on phone only

I am trying to lock the orientation of an entire app on phone sized layouts to portrait only but allow both portrait and landscape on tablet sized layouts.

I know that I can attribute the Activity to use a specific orientation but this is applied on both layout sizes.

    [Activity(
        Label = "Brs.Members.Droid"
        , MainLauncher = true
        , Icon = "@mipmap/icon"
        , Theme = "@style/Theme.Splash"
        , NoHistory = true
        , ScreenOrientation = ScreenOrientation.Portrait)]
    public class SplashScreen : MvxSplashScreenActivity
    {
        public SplashScreen() : base(Resource.Layout.SplashScreen)
        {
        }
    }

Is there a method to only exclude landscape layouts on phone size devices?

like image 422
Phil Murray Avatar asked Feb 21 '17 14:02

Phil Murray


2 Answers

Try the code below,check your device if it is tablet first and then set the orientation:

[Activity(Label = "MyOrientationDemo", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);
        if (!isPad(this))
        {
            RequestedOrientation = ScreenOrientation.Portrait;
        }
        SetContentView (Resource.Layout.Main);
    }

    public static bool isPad(Context context)
    {
        return (context.Resources.Configuration.ScreenLayout& ScreenLayout.SizeMask)>= ScreenLayout.SizeLarge;
    }
}
like image 156
Mike Ma Avatar answered Nov 10 '22 10:11

Mike Ma


What you can do is to first check if the device is tablet and then lock the orientation to portrait at run time.

Here is a useful post post to determine if the device is tablet :
Determine if the device is a smartphone or tablet?

So here is what you can do :

  1. Create a values resource file with the qualifier of Smallest screen width equal to 600dp. (sw600dp)

    Inside the file set the boolean value of isTablet to true :

    <resources>
        <bool name="isTablet">true</bool>
    </resources>
    

    Then inside the normal values file (without the screen size qualifier) set the value of isTablet to false :

    <resources>
        <bool name="isTablet">false</bool>
    </resources>
    
  2. Then get the isTablet value in onCreate and set the orientation accordingly :

    boolean isTablet = getResources().getBoolean(R.bool.isTablet);
    if (!isTablet) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }
    
like image 27
Nika Kurdadze Avatar answered Nov 10 '22 10:11

Nika Kurdadze