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 Uri("https://www.baidu.com/"));

拨打电话:

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

打开地图定位:

if (Device.OS == TargetPlatform.iOS) {
    //https://developer.apple.com/library/ios/featuredarticles/iPhoneURLScheme_Reference/MapLinks/MapLinks.html
    Device.OpenUri(new Uri("http://maps.apple.com/?q=394+Pacific+Ave+San+Francisco+CA"));
} 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(() =>
{
});

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值