Dependency Service 簡單說就是在 Xamarin Shared Code 上定義 interface,各平台實在該 interface 後,可以在 Shared Code 內呼叫使用
該圖取至官方文章
利用 IDeviceOrientation interface 來統一呼叫各平台偵測裝置方向功能
IDeviceOrientation
namespace DependencyServiceSample
{
public enum DeviceOrientations
{
Undefined,
Landscape,
Portrait
}
public interface IDeviceOrientation
{
DeviceOrientations GetOrientation();
}
}
Androidusing DependencyServiceSample.Droid;
[assembly: Xamarin.Forms.Dependency(typeof(DeviceOrientationImplementation))]
namespace DependencyServiceSample.Droid
{
public class DeviceOrientationImplementation : IDeviceOrientation
{
public DeviceOrientations GetOrientation()
{
IWindowManager windowManager = Android.App.Application.Context.GetSystemService(Context.WindowService).JavaCast<IWindowmanager>();
var rotation = windowManager.DefaultDisplay.Rotation;
bool isLandscape = rotation == SurfaceOrientation.Rotation90 || rotation == SurfaceOrientation.Rotation270;
return isLandscape ? DeviceOrientations.Landscape : DeviceOrientations.Portrait;
}
}
}
iOSusing UIKit;
using DependencyServiceSample.iOS;
[assembly: Xamarin.Forms.Dependency(typeof(DeviceOrientationImplementation))]
namespace DependencyServiceSample.iOS
{
public class DeviceOrientationImplementation : IDeviceOrientation
{
public DeviceOrientations GetOrientation()
{
var currentOrientation = UIApplication.SharedApplication.StatusBarOrientation;
bool isPortrait = currentOrientation == UIInterfaceOrientation.Portrait || currentOrientation == UIInterfaceOrientation.PortraitUpsideDown;
return isPortrait ? DeviceOrientations.Portrait : DeviceOrientations.Landscape;
}
}
}
MainPage.xaml,就放一個 Button 佔滿整個畫面<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:DependencyServiceSample"
x:Class="DependencyServiceSample.MainPage">
<Button x:Name="btnOrientations" Text="顯示裝置方向" Clicked="BtnOrientations_Clicked"></Button>
</ContentPage>
MainPage.xaml.cs,點擊 Button 會顯示裝置方向namespace DependencyServiceSample
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
private void BtnOrientations_Clicked(object sender, EventArgs e)
{
var orientation = DependencyService.Get<IDeviceorientation>().GetOrientation();
switch (orientation)
{
case DeviceOrientations.Undefined:
DisplayAlert("訊息", "未定義", "OK");
break;
case DeviceOrientations.Landscape:
DisplayAlert("訊息", "橫向", "OK");
break;
case DeviceOrientations.Portrait:
DisplayAlert("訊息", "直向", "OK");
break;
}
}
}
}
測試結果
沒有留言:
張貼留言