Xamarin.Forms ターゲット依存コードの配置
1 プロジェクトの作成
Xamarin3.0で新しく利用可能になったXamarin.Formsを試してみました。
Developers Guides Xamarin.Forms
プロジェクトは、「テンプレート」−「Visual C#」−「Mobile Apps」−「Blanck App」で作成します。
ソリューション内に作成されるのは、ターゲット毎の3種類(Android、iOS、WindowsPhone8)のプロジェクトと移植可能プロジェクトの4つです。
各ターゲット毎のプロジェクトを「スタートアッププロジェクトに設定」することで、構築が可能です。
以降、例として「Cmailの送信処理」を「ターゲットごとの依存処理(以下、"依存処理")」と位置づけてサンプルを作成してみました。
2 「依存処理」のインターフェース定義
App1(移植可能)のプロジェクトに、インターフェースを定義します。
namespace App1 { //「依存処理」のインターフェース定義 public interface ICmail{ //to宛にCmaiを送信する bool Send(string to, string message); } }
3 「依存処理」の実装
App.Andloid(ターゲット毎)プロジェクトに、先に定義したインターフェースに基づいて、「依存処理」の実装を行います。
namespace App1.Droid { //「依存処理」クラスの定義 class Cmail :ICmail{ public bool Send(string to, string message){ //Cメールを実際に送信するコード return true; } } }
4 「依存処理」オブジェクトの変数
App1(移植可能)のプロジェクトに、「依存処理」クラスの「(1)オブジェクト」、「(2)オブジェクトを受け取るメソッド」及び「(3)オブジェクトへのアクセッサ」を定義します。
「依存処理」オブジェクトは、初期化の前後関係からstaticにする必要があるようです。
namespace App1{ public class App{ public static Page GetMainPage(){ return new MyContentPage(_cmail); } //(1)「依存処理」オブジェクト private static ICmail _cmail; //(2)「依存処理」オブジェクトを受け取るメソッド public static void SetCmail(ICmail cmail){ _cmail = cmail; } //(3)「依存処理」オブジェクトへのアクセッサ public static ICmail Cmail{ get { return _cmail; } } }
5 「依存処理」オブジェクトの生成と共通プロジェクト側へのセット
App.Andloid(ターゲット毎)プロジェクトで、「依存処理」のインスタンスを生成し、App1(移植可能)のプロジェクト側の変数にセットします。
namespace App1.Droid { [Activity(Label = "App1", MainLauncher = true)] public class MainActivity : AndroidActivity { protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); //Xamarin.Formsの初期化 Xamarin.Forms.Forms.Init(this, bundle); //「依存処理」クラスを生成しApp1(移植可能)プロジェクト側の変数にセット App.SetCmail(new Cmail()); //メインページのセット SetPage(App.GetMainPage()); } } }
6 フォームの実装
App1(移植可能)のプロジェクトで、Xamarin.Formsの定義を行います。
このコードで、各ターゲットに共通したインターフェースが生成されます。
「依存処理」は、インターフェースで共通化して使用し、実装は各ターゲット毎のプロジェクト内にあると塩梅です。
namespace App1{ public class App{ public static Page GetMainPage(){ return new MyContentPage(_cmail); } } class MyContentPage : ContentPage{ public MyContentPage(ICmail cmail){ //ボタンViewを生成する var button = new Button{Text="Send CMAIL"}; //ボタンのクリック時にCメールを送信する button.Clicked += (s, a) => cmail.Send("0901234567", "テストメッセージ"); //ボタンをStackLayoutに配置する Content = new StackLayout{ Children = { button } }; } } }