カスタムViewをレイアウト用XMLで使うには

Xamarinにも書いてある*1ようにMono for AndroidでカスタムViewをレイアウト用XMLで使うには、作成したclassに特殊なコンストラクタが必要になる。この辺は本家とほぼ同じ。
ちゃんとテンプレートが用意されている。"新規作成->Mono for Android->Android View"で新しいclassを作成すると以下の様なコードを作ってくれる。

namespase Test01 {
  public class testview : View
  {
    // 下記二つのコンストラクタが必要
    public testview (Context context, IAttributeSet attrs) :
      base (context, attrs)
    {
    }

    public testview (Context context, IAttributeSet attrs, int defStyle) :
      base (context, attrs, defStyle)
    {
    }
  }
}

もちろんすでに作成しているclassにコンストラクタを追加するだけでも良い。


XMLに記述するときは以下の様に記述する。ネームスペースを小文字にしなければならないのがミソ。

<ネームスペースを小文字にした物.クラス名 .... />

例えば

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
>
  <test01.testview
    android:layout_width="match_parent"
    android:layout_height="match_parent"
  />
</FrameLayout>

こんな感じになる。

*1:http://docs.xamarin.com/android/advanced_topics/using_custom_views_in_a_layout