Xamarin.Android
ファイル構成
新しいプロジェクトとしてAndroidのプロジェクト(以下、Xamarin.Android)を作成した場合の主な構成を見てみましょう。JavaによるAndroidアプリ開発の経験があるならば、その構成と比較しながら見てみると、より理解しやすいと思います。
MainActivity.cs
プログラムの起点となるファイルです。Xamarin.Androidらしい特徴的な箇所がいくつかあるのでコードを確認してみましょう。
[Activity(Label = "App1", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
int count = 1;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
// Get our button from the layout resource,
// and attach an event to it
Button button = FindViewById<Button>(Resource.Id.MyButton);
button.Click += delegate { button.Text = string.Format("{0} clicks!", count++); };
}
}
「MainLauncher = true」は、このクラスがアプリケーションが起動時に読み込まれるアクティビティであることを指定しています。
「Button button = FindViewById<Button>(Resource.Id.MyButton);」はAndroidで画面(View)のコントロールを取得するAndroidらしいコードですが、「button.Click += delegate」以下のコードはC#のdelegateを用いてボタンをクリックした際のイベントハンドラーを指定するC#らしい記述です。
このようにXamarinでは、プラットフォーム(この場合Xamarin.Android)固有の記述とC#らしい記述を組み合わせることができます。
Main.axml
先ほどのMainActivity.csの「SetContentView」メソッドで指定されていた画面の表示について記述したファイルです。
XamarinはViewの仕組みを各プラットフォームの定義方法に準拠しており、Main.axmlは以下のようなXMLで記述されています。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:id="@+id/MyButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/Hello" />
</LinearLayout>
この記述はJavaを用いたAndroid開発で利用するXMLと同じものです。実際にJavaで作成したAndroidアプリの画面定義のXMLをコピーして、Xamarin.Androidで利用できることを確認しています。
このようにXamarinでは基本的にViewはそれぞれのプラットフォームに依存しています(後述するXamarin.Formを除いて)。
Strings.xml
アプリケーションで利用する文字列などのリソースを定義します。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="Hello">Hello World, Click Me!</string>
<string name="ApplicationName">App1</string>
</resources>
デバッグする
Xamarin.AndroidのデバッグはJava+Eclipseでの開発同様、実機かエミュレーターにアプリのパッケージを転送することで行います。
エミュレーターは同じ仕組みを用いるため、起動に非常に時間がかかるのも同様です。さまざまな端末をエミュレートできるのは魅力ですが、開発時は実機があると作業が捗ります。
また、インストール直後の状態だとAPIレベルが10か12のエミュレーターしか用意されていないにも関わらず、プロジェクトのMinimum Android to target(最少のターゲット)のAPIレベルが15に設定されているので、エミュレーターを更新ないし追加するか、プロジェクトのプロパティのMinimum Android to targetのAPI Levelを変更しておくと良いでしょう。

