Xamarin.Essentials:プラットフォーム拡張

Xamarin.Essentials からは、プラットフォームの種類を使用する必要があるとき、Rect、Size、Point など、プラットフォーム拡張メソッドがいくつか提供されます。 つまり、iOS、Android、UWP 固有の種類に対して、これらの種類の System バージョン間で変換できます。

作業開始

この API の使用を始めるには、Xamarin.Essentials の概要ガイドを読み、ライブラリが正しくインストールされてプロジェクトに設定されていることを確認してください。

プラットフォーム拡張の使用

クラスの Xamarin.Essentials への参照を追加します。

using Xamarin.Essentials;

プラットフォーム拡張はすべて、iOS、Android、UWP プロジェクトからのみ呼び出すことができます。

Android の拡張機能

これらの拡張機能には、Android プロジェクトからのみアクセスできます。

アプリケーション コンテキストおよびアクティビティ

Platform クラスのプラットフォーム拡張を使用すると、実行中のアプリの現在の Context または Activity にアクセスできます。


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();

アクティビティのライフサイクル

現在のアクティビティを取得するだけでなく、ライフサイクル イベントに登録することもできます。

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();

アクティビティの状態は次のとおりです。

  • Created
  • Resumed
  • Paused
  • Destroyed
  • SaveInstanceState
  • Started
  • Stopped

詳細については、「アクティビティのライフサイクル」のドキュメントを参照してください。

iOS の拡張機能

これらの拡張機能には、iOS プロジェクトからのみアクセスできます。

現在の UIViewController

現在表示されている UIViewController にアクセスできるようにします。

var vc = Platform.GetCurrentUIViewController();

UIViewController を検出できない場合、このメソッドでは null が返されます。

クロスプラットフォーム拡張機能

次の拡張機能は、すべてのプラットフォームで存在します。

ポイント

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();

Rectangle

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