Xamarin.Forms Device類介紹

Device是一個靜態(tài)類,提供一些屬性和方法幫助開發(fā)者判斷平臺類型、對不同平臺提供不同處理。

Device.Idiom

Idiom屬性,TargetIdiom枚舉類型。可以根據(jù)Idiom判斷當前設備的類型。

使用方式,移動端開發(fā)主要判斷Phone和Tablet(平板):

Device.OS

OS屬性,TargetPlatform枚舉類型。判斷當前設備系統(tǒng)平臺。

如單獨設置iOS的Padding,解決頁面與狀態(tài)欄重疊問題:

Device.OnPlatform

Device提供了兩個OnPlatform方法。一個是范型方法,根據(jù)不同不同平臺,返回對應設置的值,內部通過判斷Device.OS屬性實現(xiàn)。

XAML使用示例:

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

還提供了一個接收Action類型參數(shù)的OnPlatform方法,會根據(jù)不同平臺執(zhí)行不同的動作。

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類型參數(shù)和一個Type類型參數(shù),根據(jù)傳入的NamedSize返回當前平臺Type類型對應最適合的值。

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

Device.OpenUri

根據(jù)傳入的Uri調用系統(tǒng)提供的內置功能。

打開網(wǎng)頁:

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時間會執(zhí)行Func<bool>對應的動作。當Func<bool>返回false時,定時器停止。

創(chuàng)建一個周期為1秒的定時器:

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

Device. BeginInvokeOnMainThread

用戶界面的相關操作是不允許在后臺線程中執(zhí)行。子線程中執(zhí)行用戶界面更新操作需要將代碼放在BeginInvokeOnMainThread中執(zhí)行,BeginInvokeOnMainThread作用類似于iOS中的InvokeOnMainThread, Android中的RunOnUiThread, Windows Phone中的Dispatcher.BeginInvoke。

Device.BeginInvokeOnMainThread(() =>
{
});
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容