Reputation: 65
I have a requirement to rotate the screen to Landscape from Portrait. Then I should stay in Landscape even though I have not tilted my phone. Portrait and Landscape have different views with buttons for orientation change and is in same content page which I have handled with content template. So, now I wanted to rotate automatically if I tilt the phone or if I tap on the button in either view to change orientation.
I want to satisfy both cases. How to achieve that in Android and iOS (Xamarin.Forms)?
Anyone faces this kind of usecase and if you got a solution. Help me out.
Upvotes: 0
Views: 1155
Reputation: 10938
When using Xamarin.Forms, the supported method of controlling device orientation is to use the settings for each individual project.
You could call the following method in dependency service.
Create a interface:
public interface IOrientationService
{
void Landscape();
void Portrait();
}
Android:
public class OrientationService : IOrientationService
{
public void Landscape()
{
((Activity)Forms.Context).RequestedOrientation = ScreenOrientation.Landscape;
}
public void Portrait()
{
((Activity)Forms.Context).RequestedOrientation = ScreenOrientation.Portrait;
}
}
iOS:
public class OrientationService : IOrientationService
{
public void Landscape()
{
AppDelegate appDelegate = (AppDelegate)UIApplication.SharedApplication.Delegate;
appDelegate.allowRotation = true;
UIDevice.CurrentDevice.SetValueForKey(new NSNumber((int)UIInterfaceOrientation.LandscapeLeft), new NSString("orientation"));
}
public void Portrait()
{
AppDelegate appDelegate = (AppDelegate)UIApplication.SharedApplication.Delegate;
appDelegate.allowRotation = true;
UIDevice.CurrentDevice.SetValueForKey(new NSNumber((int)UIInterfaceOrientation.Portrait), new NSString("orientation"));
}
}
For the usage of dependency service, you could refer to the link below. How can I block rotation to only allow portrait mode in xamarin forms?
- I want to rotate only one page in my app automatically and as well as manually.
When you do the navigation, you could do the Orientation before loading the page in OnAppearing
event.
protected override void OnAppearing()
{
base.OnAppearing();
DependencyService.Get<IOrientationService>().Landscape();
}
- Both portrait and landscape views are different.
Liek 1., you could set the Orientation you want to in each page with OnAppearing()
event.
- I should not lock the particular page at any cause but I also when I want to change orientation manually I should able to do that. Even though I am not rotating/tilt the phone.
If you want to do it manually, invoke the Landscape
or Portrait
in a click event or tap or something else.
Upvotes: 2