Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect screen orientation of the device in Xamarin.Forms?

How to detect screen orientation change in Xamarin Forms? I need to change the view on orientation change, what should I do to trigger a change on orientation change? Providing a link or sample code would be very helpful.

Thanks in advance

like image 208
Femil Shajin Avatar asked Jul 09 '14 14:07

Femil Shajin


People also ask

How to detect device orientation in Xamarin forms?

To detect orientations without Xamarin. Essentials, monitor the SizeChanged event of the Page , which fires when either the width or height of the Page changes. When the width of the Page is greater than the height, the device is in landscape mode. For more information, see Display an Image based on Screen Orientation.

How do you handle rotation?

If you want to manually handle orientation changes in your app you must declare the "orientation" , "screenSize" , and "screenLayout" values in the android:configChanges attributes. You can declare multiple configuration values in the attribute by separating them with a pipe | character.

What is screen orientation?

Screen Orientation, also known as screen rotation, is the attribute of activity element in android. When screen orientation change from one state to other, it is also known as configuration change.


2 Answers

I tried it with dependency injection, but no succes yet. Right now, I solved it like this:

  • Use OnSizeAllocated(double, double) for changing the screen on orientation changes.
  • Use a Singleton for storing the current orientation.

Xamarin.Forms Page

protected override void OnSizeAllocated(double width, double height)
{
    base.OnSizeAllocated(width, height);

    if (DeviceInfo.IsOrientationPortrait() && width > height || !DeviceInfo.IsOrientationPortrait() && width < height)
        {
            // Orientation got changed! Do your changes here
        }
}

Singleton Class

public class DeviceInfo
{
    protected static DeviceInfo _instance;
    double width;
    double height;

    static DeviceInfo()
    {
        _instance = new DeviceInfo();
    }
    protected DeviceInfo()
    {
    }

    public static bool IsOrientationPortrait() 
    {
        return _instance.height > _instance.width;
    }

    public static void SetSize(double width, double height)
    {
        _instance.width = width;
        _instance.height = height;
    }
}
like image 195
bkardol Avatar answered Oct 23 '22 03:10

bkardol


Just add this to your Page, or better yet your BasePage:

 static bool IsPortrait(Page p) { return p.Width < p.Height; }
like image 26
Ian Vink Avatar answered Oct 23 '22 03:10

Ian Vink