Giter VIP home page Giter VIP logo

xamarin.plugin.deviceorientation's Introduction

Device Orientation Plugin for Xamarin and Windows

Simple cross-platform plugin to work with screen orientation of mobile device.

iOS demo

Xamarin.Forms sample

Setup

  • Available on NuGet: NuGet Badge
  • Install into your PCL/NetStandard project and Platform Specific projects

Platform Support

Platform Version
Xamarin.iOS iOS 10+
Xamarin.Android API 19+
Windows 10 UWP 10.0.16299+

v2.0 updated to NetStandard 2.0

Deprecated platforms

  • Windows Phone Silverlight
  • Windows Phone RT
  • Windows Store RT

Implementations for unsupported platforms contains here.

API Usage

Call CrossDeviceOrientation.Current from any project or PCL to gain access to APIs.

/// <summary>
/// Gets current device orientation
/// </summary>
DeviceOrientations CurrentOrientation { get; }

When device orientation is changed you can register for an event to fire:

/// <summary>
/// Event handler when orientation changes
/// </summary>
event OrientationChangedEventHandler OrientationChanged;

You will get a OrientationChangedEventArgs with the orientation type:

public class OrientationChangedEventArgs : EventArgs
{
	public DeviceOrientations Orientation { get; set; }
}

public delegate void OrientationChangedEventHandler(object sender, OrientationChangedEventArgs e);

The DeviceOrientations enumeration has these members.

Member Value Description
Undefined 0 No display orientation is specified.
Landscape 1 Specifies that the monitor is oriented in landscape mode where the width of the display viewing area is greater than the height.
Portrait 2 Specifies that the monitor rotated 90 degrees in the clockwise direction to orient the display in portrait mode where the height of the display viewing area is greater than the width.
LandscapeFlipped 4 Specifies that the monitor rotated another 90 degrees in the clockwise direction (to equal 180 degrees) to orient the display in landscape mode where the width of the display viewing area is greater than the height. This landscape mode is flipped 180 degrees from the Landscape mode.
PortraitFlipped 8 Specifies that the monitor rotated another 90 degrees in the clockwise direction (to equal 270 degrees) to orient the display in portrait mode where the height of the display viewing area is greater than the width. This portrait mode is flipped 180 degrees from the Portrait mode.

Call LockOrientation for set orientation and lock with disabling device auto-rotation:

/// <summary>
///     Lock orientation in the specified position
/// </summary>
/// <param name="orientation">Position for lock.</param>
void LockOrientation(DeviceOrientations orientation);

For disable the lock, call UnlockOrientation method:

/// <summary>
///     Unlock orientation
/// </summary>
void UnlockOrientation();

iOS Specific Support

Add this code for your ViewController where you want locking orientation:

public override bool ShouldAutorotate()
{
	// set plugin for handle of this method
	return DeviceOrientationImplementation.ShouldAutorotate;
}

public override UIInterfaceOrientationMask GetSupportedInterfaceOrientations()
{
	// allow all orientations
	return UIInterfaceOrientationMask.AllButUpsideDown;
}

In your Info.plist need set all device orientations.

Xamarin.Forms iOS

If you want to lock orientation for the entire iOS application.

Add this code in your AppDelegate.cs:

[Export("application:supportedInterfaceOrientationsForWindow:")]
public UIInterfaceOrientationMask GetSupportedInterfaceOrientations(UIApplication application, IntPtr forWindow)
{
    return DeviceOrientationImplementation.SupportedInterfaceOrientations;
}

Note: In this case, to lock/unlock orientation on the one screen, you must use the LockOrientation/UnlockOrientation methods.

Xamarin.Forms Android

In your MainActivity.cs, add overriding for changing orientation as here:

public override void OnConfigurationChanged(Configuration newConfig)
{
    base.OnConfigurationChanged(newConfig);

    DeviceOrientationImplementation.NotifyOrientationChange(newConfig.Orientation);
}

Note: This solution has only two state Portrait and Landscape.

Additional information

Troubleshooting

Contributors


ยฉ 2016-2019 MIT License

xamarin.plugin.deviceorientation's People

Contributors

wcoder avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

xamarin.plugin.deviceorientation's Issues

Where is v2.0

In the device compatibility, this is listed: v2.0 updated to NetStandard 2.0, but there is no v2.0 and the Plugin doesn't work with iOS with NetStandard 2.0.

NullReferenceException on Android

On android with:

String s = CrossDeviceOrientation.Current.CurrentOrientation.ToString();

I get:

System.NullReferenceException: 
Object reference not set to an instance of an object.

Working normally on Windows Phone.

Is there any way to prevent the orientation change?

Hi,
I want to prevent the app to be rotated to portrait mode in certain scenarios, but I need it available so I can't disable it completely.
I know we have the OrientationChanged event but it fires after the orientation changes.

In other words; I want the app to be available in landscape and landscape flipped mode.
How can I achieve this?

I'm currently using Xamarin.Forms with PCL.

CurrentOrientation is reversed on some Android tablets

CrossDeviceOrientation.Current.CurrentOrientation is reversed on some Android tablets. I guess this is because some tablets are in landscape mode by default. We could reproduce this with:

  • Sony Xperia Tablet Z2 (android 5.1.1)
  • Google pixel c (android 8.1.0)
  • Google Nexus 10 (android 5.1.1)
  • Samsung Galaxy Tab 4

I suspect there are many more devices with this problem. We could't reproduce it with emulators or any smartphone.

activity.Resources.Configuration.Orientation returns Landscape

activity.WindowManager.DefaultDisplay.Rotation returns Rotation180 and is converted by your plugin to DeviceOrientations.PortraitFlipped but this is wrong.

activity.WindowManager.DefaultDisplay is deprecated since API Level 11, this should be replaced with a more recent solution

probably related to #10

LockOrientation not working on tablet

Hello, I do this:

        if (Settings.OrientationSwitch)
        {
            DeviceOrientations selectedOrientation = Settings.Orientation == 0 ? DeviceOrientations.Portrait : DeviceOrientations.Landscape;

            CrossDeviceOrientation.Current.LockOrientation(selectedOrientation);
        }

Is working perfectly on iOS mobile, but is not working when I deploy to tablet devices. Any idea?

Thank you!

App crashes when I lock orientation to PortraitFlipped

Hi, in my app I need to change to PortraitFlipped at one time. But when I try to do this, the app crashes with this error:
Foundation.MonoTouchException: Objective-C exception thrown. Name: UIApplicationInvalidInterfaceOrientation Reason: Supported orientations has no common orientation with the application, and [Xamarin_Forms_Platform_iOS_PlatformRenderer shouldAutorotate] is returning YES

This is my Info.plist:

<key>UISupportedInterfaceOrientations</key>
<array>
	<string>UIInterfaceOrientationPortrait</string>
	<string>UIInterfaceOrientationPortraitUpsideDown</string>
	<string>UIInterfaceOrientationLandscapeLeft</string>
	<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
	<string>UIInterfaceOrientationPortrait</string>
	<string>UIInterfaceOrientationPortraitUpsideDown</string>
	<string>UIInterfaceOrientationLandscapeLeft</string>
	<string>UIInterfaceOrientationLandscapeRight</string>
</array>

In my AppDelegate I have put this:

[Export("application:supportedInterfaceOrientationsForWindow:")]
public UIInterfaceOrientationMask GetSupportedInterfaceOrientations(UIApplication application, IntPtr forWindow)
{
	return DeviceOrientationImplementation.SupportedInterfaceOrientations;
}

The other orientations are not causing trouble.
I am working with Xamarin.Forms, the device is an iPhone 8 and the crash occurs both on the real device and simulator.

Build warning: Using a deprecated debug information level.

First of all, thank you @wcoder for this plugin. It's great and really does the job for us ๐Ÿ‘

-- The issue --
We get this build warning. Thank you for updating the code accordingly or please let me know if this is a configuration issue I can fix on my end.
Warning XA0125: 'Plugin.DeviceOrientation.pdb' is using a deprecated debug information level.

Comparing orientations?

What is the correct way to do orientation comparisons? I've tried the following, none of which work:

bool fail1 = CrossDeviceOrientation.Current == 2;
bool fail2 = CrossDeviceOrientation.Current == DeviceOrientations.Portrait;
bool fail3 = CrossDeviceOrientation.Current.Equals(DeviceOrientations.Portrait);

Coming from Swift/Obj-C, I'm sure there is some dumb thing I am doing here. Also, would be great if you included an example like this in the docs.

Getting a NullReferenceException

I am using this plugin in my xamarin forms app. But when I want to change the orientation to Landscape app getting crash and giving me a NullReferenceException in Android.

Android version 9(Pie)
Xamarin.Forms version is 4.2.0.848062

Orientation lock does not work on iOS

Tried to use the nuget package without success, so I cloned the repo and started the sample app on an ipad with ios 11.3.1.

Screen rotates even if label says locked...

This is the case for both the samples-solution and the TestNugetDeviceOrientationPlugin

Android: Cannot access a disposed object.

DeviceOrientationImplementation.set_IsListenerEnabled (System.Boolean value)
System.ObjectDisposedException: Cannot access a disposed object. Object name: 'Plugin.DeviceOrientation.OrientationListener'.

This is thrown when the following override in the MainActivity is called after switching away from app and then back to app:
public override void OnConfigurationChanged(Android.Content.Res.Configuration newConfig)
{
DeviceOrientationImplementation.NotifyOrientationChange(newConfig.Orientation);
}

Repo steps:
Tested on Android v8 and v9

  • Implement override so that NotifyOrientationChange is called in Android
  • Open app and use so the LockOrientation is called
  • Put app in background
  • Put app back in foreground
  • When changing the orientation, the app will crash because the OrientationListener is disposed.

Add SetCurrentActivityResolver + Remove dependency to Plugin.CurrentActivity

Currently, Xamarin.Plugin.DeviceOrientation uses the Plugin.CurrentActivity nuget package in the Android implementation to access the current activity. This is the same behavior as many plugins use. However, since the rise of Xamarin.Essentials (which also offers access to Android's current activity), I would propose to eliminate the direct dependency to Plugin.CurrentActivity. Instead, I'd add a new static method to CrossDeviceOrientation: SetCurrentActivityResolver(Func activityResolver) which dynamically resolves the current activity from either Plugin.CurrentActivity or Xamarin.Essentials (or another plugin).

A similar solution is successfully used in the Fingerprint plugin (https://github.com/smstuebe/xamarin-fingerprint). Check the following CrossFingerprint.Android.cs file:
https://github.com/smstuebe/xamarin-fingerprint/blob/9fb42c4a8b620260c0c03eb2714e2e03a92d472b/src/Plugin.Fingerprint/Platforms/Android/CrossFingerprint.Android.cs

What do you think of this proposal for extension?

Landscape and Portrait switched in Android

On iOS, everything is perfectly fine, but as soon as I use this on Android, everything is switched around? When I rotate the device and print out the orientation, it says it is Landscape, when it is actually Portrait?

Here is my custom Image class where the error exists:

using Plugin.DeviceOrientation;
using Plugin.DeviceOrientation.Abstractions;
using System;
using System.Collections.Generic;
using System.Text;
using Xamarin.Forms;

namespace Project.Custom
{
    public class DSImage : Image
    {
        public DSImage(int phonePortrait, int phoneLandscape, int tabletPortrait, int tabletLandscape)
        {
            if (Device.Idiom == TargetIdiom.Phone)
            {
                if (CrossDeviceOrientation.Current.CurrentOrientation == DeviceOrientations.Portrait || CrossDeviceOrientation.Current.CurrentOrientation == DeviceOrientations.PortraitFlipped)
                {
                    System.Diagnostics.Debug.WriteLine("Phone Portrait");
                    HeightRequest = phonePortrait;
                }
                else if (CrossDeviceOrientation.Current.CurrentOrientation == DeviceOrientations.Landscape || CrossDeviceOrientation.Current.CurrentOrientation == DeviceOrientations.LandscapeFlipped)
                {
                    System.Diagnostics.Debug.WriteLine("Phone Landscape");
                    HeightRequest = phoneLandscape;
                }
            }
            else if (Device.Idiom == TargetIdiom.Tablet)
            {
                if (CrossDeviceOrientation.Current.CurrentOrientation == DeviceOrientations.Portrait || CrossDeviceOrientation.Current.CurrentOrientation == DeviceOrientations.PortraitFlipped)
                {
                    System.Diagnostics.Debug.WriteLine("Tablet Portrait");
                    HeightRequest = tabletPortrait;
                }
                else if (CrossDeviceOrientation.Current.CurrentOrientation == DeviceOrientations.Landscape || CrossDeviceOrientation.Current.CurrentOrientation == DeviceOrientations.LandscapeFlipped)
                {
                    System.Diagnostics.Debug.WriteLine("Tablet Landscape");
                    HeightRequest = tabletLandscape;
                }
            }

            CrossDeviceOrientation.Current.OrientationChanged += (sender, args) =>
            {
                if (Device.Idiom == TargetIdiom.Phone)
                {
                    if (CrossDeviceOrientation.Current.CurrentOrientation == DeviceOrientations.Portrait || CrossDeviceOrientation.Current.CurrentOrientation == DeviceOrientations.PortraitFlipped)
                    {
                        System.Diagnostics.Debug.WriteLine("Phone Portrait");
                        HeightRequest = phonePortrait;
                    }
                    else if (CrossDeviceOrientation.Current.CurrentOrientation == DeviceOrientations.Landscape || CrossDeviceOrientation.Current.CurrentOrientation == DeviceOrientations.LandscapeFlipped)
                    {
                        System.Diagnostics.Debug.WriteLine("Phone Landscape");
                        HeightRequest = phoneLandscape;
                    }
                }
                else if (Device.Idiom == TargetIdiom.Tablet)
                {
                    if (CrossDeviceOrientation.Current.CurrentOrientation == DeviceOrientations.Portrait || CrossDeviceOrientation.Current.CurrentOrientation == DeviceOrientations.PortraitFlipped)
                    {
                        System.Diagnostics.Debug.WriteLine("Tablet Portrait");
                        HeightRequest = tabletPortrait;
                    }
                    else if (CrossDeviceOrientation.Current.CurrentOrientation == DeviceOrientations.Landscape || CrossDeviceOrientation.Current.CurrentOrientation == DeviceOrientations.LandscapeFlipped)
                    {
                        System.Diagnostics.Debug.WriteLine("Tablet Landscape");
                        HeightRequest = tabletLandscape;
                    }
                }
            };
        }
    }
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.