Android では View を XML ファイルから構築できます。
この機能で構築した View を画面の要素に Add することで画面の一部だけを XML で定義できることになります。
何がうれしいの?
この機能を使うと、複数の画面で出てくる同じ要素の組み合わせの定義を共有したり、画面上の状況によって表示の変わる部分を切り出して定義できたりします。
ポップアップの表示にも使えたりします。
また、Android で View の要素一つづつを new してAddView して組み上げるコードは決して短くありません。
場合によっては、XML の文字列を構築する方がスマートなこともあるかもしれません(やったことはありませんが)。
LayoutInflater.Inflate メソッド
LayoutInflater の Inflate メソッドを使用します。
コード
次のようなコードになります。
レイアウト定義
・Main.amxl 通常の画面定義
<?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" android:id="@+id/ll" android:background="@android:color/background_light" android:padding="10dp"/>
・XMLFile1.xml 今回動的に追加する要素の定義
<?xml version="1.0" encoding="utf-8" ?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@android:color/background_dark"> <TextView android:text="test" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </LinearLayout>
Activity のコード
・MainActivity.cs
public class MainActivity : Activity { protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.Main); var v1 = LayoutInflater.Inflate(Resource.Layout.XMLFile1, null); // XMLFile1 の内容 var root = FindViewById<ViewGroup>(Android.Resource.Id.Content); // Main.axml の内容 var main = (ViewGroup)root.GetChildAt(0); // id/ll の LinearLayout main.AddView(v1); } }