Device是一個(gè)靜態(tài)類,提供一些屬性和方法幫助開發(fā)者判斷平臺(tái)類型贮乳、對(duì)不同平臺(tái)提供不同處理忧换。
Device.Idiom
Idiom屬性,TargetIdiom枚舉類型塘揣“福可以根據(jù)Idiom判斷當(dāng)前設(shè)備的類型。
使用方式亲铡,移動(dòng)端開發(fā)主要判斷Phone和Tablet(平板):
Device.OS
OS屬性才写,TargetPlatform枚舉類型葡兑。判斷當(dāng)前設(shè)備系統(tǒng)平臺(tái)。
如單獨(dú)設(shè)置iOS的Padding赞草,解決頁面與狀態(tài)欄重疊問題:
Device.OnPlatform
Device提供了兩個(gè)OnPlatform方法讹堤。一個(gè)是范型方法,根據(jù)不同不同平臺(tái)厨疙,返回對(duì)應(yīng)設(shè)置的值洲守,內(nèi)部通過判斷Device.OS屬性實(shí)現(xiàn)。
XAML使用示例:
<OnPlatform x:TypeArguments="Color"
iOS="Green"
Android="#738182"
WinPhone="Accent" />
還提供了一個(gè)接收Action類型參數(shù)的OnPlatform方法,會(huì)根據(jù)不同平臺(tái)執(zhí)行不同的動(dòng)作沾凄。
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
不同平臺(tái)效果圖:
XAML使用示例:
<Label Text="TitleStyle" VerticalOptions="Center" HorizontalOptions="Center"
Style="{DynamicResource TitleStyle}" />
C#使用示例:
new Label
{
Text = "TitleStyle",
Style = Device.Styles.TitleStyle
};
Device.GetNamedSize
接收一個(gè)NamedSize類型參數(shù)和一個(gè)Type類型參數(shù),根據(jù)傳入的NamedSize返回當(dāng)前平臺(tái)Type類型對(duì)應(yīng)最適合的值撒蟀。
var label = new Label();
label.FontSize = Device.GetNamedSize(NamedSize.Small, typeof(Label));
Device.OpenUri
根據(jù)傳入的Uri調(diào)用系統(tǒng)提供的內(nèi)置功能叙谨。
打開網(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
啟動(dòng)一個(gè)簡單的定時(shí)器,每隔TimeSpan時(shí)間會(huì)執(zhí)行Func<bool>對(duì)應(yīng)的動(dòng)作保屯。當(dāng)Func<bool>返回false時(shí)手负,定時(shí)器停止。
創(chuàng)建一個(gè)周期為1秒的定時(shí)器:
Device.StartTimer(new TimeSpan(0, 0, 1), () =>
{
label.Text = DateTime.Now.ToString("F");
return true;
});
Device. BeginInvokeOnMainThread
用戶界面的相關(guān)操作是不允許在后臺(tái)線程中執(zhí)行姑尺。子線程中執(zhí)行用戶界面更新操作需要將代碼放在BeginInvokeOnMainThread
中執(zhí)行竟终,BeginInvokeOnMainThread作用類似于iOS中的InvokeOnMainThread, Android中的RunOnUiThread, Windows Phone中的Dispatcher.BeginInvoke。
Device.BeginInvokeOnMainThread(() =>
{
});