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
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.
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.
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.
I tried it with dependency injection, but no succes yet. Right now, I solved it like this:
OnSizeAllocated(double, double)
for changing the screen on orientation changes.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;
}
}
Just add this to your Page, or better yet your BasePage:
static bool IsPortrait(Page p) { return p.Width < p.Height; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With