您的当前位置:首页正文

Xamarin.Forms Device类介绍

来源:华拓网

Device是一个静态类,提供一些属性和方法帮助开发者判断平台类型、对不同平台提供不同处理。

Device.Idiom

Idiom属性,TargetIdiom枚举类型。可以根据Idiom判断当前设备的类型。

使用方式,移动端开发主要判断Phone和Tablet(平板):

Device.OS

OS属性,TargetPlatform枚举类型。判断当前设备系统平台。

如单独设置iOS的Padding,解决页面与状态栏重叠问题:

Device.OnPlatform

Device提供了两个OnPlatform方法。一个是范型方法,根据不同不同平台,返回对应设置的值,内部通过判断Device.OS属性实现。

XAML使用示例:

<OnPlatform x:TypeArguments="Color"
      iOS="Green"
      Android="#738182"
      WinPhone="Accent" />

还提供了一个接收Action类型参数的OnPlatform方法,会根据不同平台执行不同的动作。

OnPlatform does not currently support differentiating the Windows 8.1, Windows Phone 8.1, and UWP/Windows 10 platforms.

Device.Styles

提供了定义好的适用于Label样式。包括:

  • BodyStyle
  • CaptionStyle
  • ListItemDetailTextStyle
  • ListItemTextStyle
  • SubtitleStyle
  • TitleStyle

不同平台效果图:

XAML使用示例:

<Label Text="TitleStyle" VerticalOptions="Center" HorizontalOptions="Center" 
Style="{DynamicResource TitleStyle}" />

C#使用示例:

new Label
{
    Text = "TitleStyle",
    Style = Device.Styles.TitleStyle
};

Device.GetNamedSize

接收一个NamedSize类型参数和一个Type类型参数,根据传入的NamedSize返回当前平台Type类型对应最适合的值。

var label = new Label();
label.FontSize = Device.GetNamedSize(NamedSize.Small, typeof(Label));

Device.OpenUri

根据传入的Uri调用系统提供的内置功能。

打开网页:

Device.OpenUri(new 

拨打电话:

Device.OpenUri(new Uri("tel:10086"));

打开地图定位:

if (Device.OS == TargetPlatform.iOS) {
    
    Device.OpenUri(new 
} else if (Device.OS == TargetPlatform.Android) {
    // opens the Maps app directly
    Device.OpenUri(new Uri("geo:0,0?q=394+Pacific+Ave+San+Francisco+CA"));
} else if (Device.OS == TargetPlatform.Windows || Device.OS == TargetPlatform.WinPhone) {
    Device.OpenUri(new Uri("bingmaps:?where=394 Pacific Ave San Francisco CA"));
}

Device.StartTimer

启动一个简单的定时器,每隔TimeSpan时间会执行Func<bool>对应的动作。当Func<bool>返回false时,定时器停止。

创建一个周期为1秒的定时器:

Device.StartTimer(new TimeSpan(0, 0, 1), () =>
{
    label.Text = DateTime.Now.ToString("F");
    return true;
});

Device. BeginInvokeOnMainThread

用户界面的相关操作是不允许在后台线程中执行。子线程中执行用户界面更新操作需要将代码放在BeginInvokeOnMainThread中执行,BeginInvokeOnMainThread作用类似于iOS中的InvokeOnMainThread, Android中的RunOnUiThread, Windows Phone中的Dispatcher.BeginInvoke。

Device.BeginInvokeOnMainThread(() =>
{
});