Share via


Xamarin.Essentials:平臺延伸模組

Xamarin.Essentials 使用 Rect、Size 和 Point 等平台類型時,會提供數個平臺擴充方法。 這代表您可在 System 版的這些類型 (其 iOS、Android 及 UWP 特定類型) 間轉換。

開始使用

若要開始使用此 API,請閱讀 入門指南Xamarin.Essentials,以確保連結庫已正確安裝並設定在您的專案中。

使用平台擴充

在類別中新增 的 Xamarin.Essentials 參考:

using Xamarin.Essentials;

全部的平台擴充模組皆僅可從 iOS、Android 或 UWP 專案呼叫。

Android 擴充

這些擴充只能從 Android 專案存取。

應用程式內容與活動

透過使用 Platform 類別中的平台擴充,您可以存取執行中應用程式目前的 ContextActivity


var context = Platform.AppContext;

// Current Activity or null if not initialized or not started.
var activity = Platform.CurrentActivity;

如果有需要 Activity 的情況,但應用程式尚未完全啟動,則應該使用 WaitForActivityAsync 方法。

var activity = await Platform.WaitForActivityAsync();

活動開發週期

除了取得目前的 Activity 之外,您也可以註冊生命週期事件。

protected override void OnCreate(Bundle bundle)
{
    base.OnCreate(bundle);

    Xamarin.Essentials.Platform.Init(this, bundle);

    Xamarin.Essentials.Platform.ActivityStateChanged += Platform_ActivityStateChanged;
}

protected override void OnDestroy()
{
    base.OnDestroy();
    Xamarin.Essentials.Platform.ActivityStateChanged -= Platform_ActivityStateChanged;
}

void Platform_ActivityStateChanged(object sender, Xamarin.Essentials.ActivityStateChangedEventArgs e) =>
    Toast.MakeText(this, e.State.ToString(), ToastLength.Short).Show();

Activity 的狀態如下:

  • 建立時間
  • 已繼續
  • 已暫停
  • 終結
  • SaveInstanceState
  • 已開始
  • 已停止

請參閱活動生命週期 \(部分機器翻譯\) 文件以深入了解。

iOS 延伸模組

這些擴充只能從 iOS 專案存取。

目前的 UIViewController

取得目前可見 UIViewController 的存取權:

var vc = Platform.GetCurrentUIViewController();

如果無法偵測到 UIViewController,此方法將會傳回 null

跨平台擴充

這些擴充存在於每一個平台。

Point

var system = new System.Drawing.Point(x, y);

// Convert to CoreGraphics.CGPoint, Android.Graphics.Point, and Windows.Foundation.Point
var platform = system.ToPlatformPoint();

// Back to System.Drawing.Point
var system2 = platform.ToSystemPoint();

大小

var system = new System.Drawing.Size(width, height);

// Convert to CoreGraphics.CGSize, Android.Util.Size, and Windows.Foundation.Size
var platform = system.ToPlatformSize();

// Back to System.Drawing.Size
var system2 = platform.ToSystemSize();

矩形

var system = new System.Drawing.Rectangle(x, y, width, height);

// Convert to CoreGraphics.CGRect, Android.Graphics.Rect, and Windows.Foundation.Rect
var platform = system.ToPlatformRectangle();

// Back to System.Drawing.Rectangle
var system2 = platform.ToSystemRectangle();

API