Layoutリソースのファイルはres/layout/filename.xmlに配置します。filenameは任意の名前であり、それが「リソースID」となります。
このXML形式のファイルを、レイアウト ファイル (layout file) と呼びます。
<?xml version="1.0" encoding="utf-8"?>
<ViewGroup xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@[+][package:]id/resource_name"
android:layout_width =["dimension" | "fill_parent" | "wrap_content"]
android:layout_height=["dimension" | "fill_parent" | "wrap_content"]
[ ViewGroup-specific attributes ] >
<View
android:id="@[+][package:]id/resource_name"
android:layout_width =["dimension" | "fill_parent" | "wrap_content"]
android:layout_height=["dimension" | "fill_parent" | "wrap_content"]
[ View-specific attributes ] >
<requestFocus />
</View>
<ViewGroup >
<View />
</ViewGroup>
<include layout="@layout/layout_resource" />
</ViewGroup>
「@」以下に続く文字列はリソース名を表し、「+」はそれが新しいリソースであることを意味します。Declaring Layout | Android Developers
ルート要素は、ViewGroupまたはViewクラスを継承したクラスの要素とする必要があります。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<TextView android:text="TextView"
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<ImageView android:src="@drawable/violet"
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<com.example.MyButton android:text="Button"
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
独自に作成したクラスは、パッケージ名も含めて記述します。
ActivityクラスのgetLayoutInflater()で、LayoutInflaterクラスのインスタンスを取得します。そしてそのLayoutInflaterのinflate()を呼び出すことで、指定のViewGroupにLayoutリソースを追加できます。
public LayoutInflater getLayoutInflater ()
public View inflate (
int resource, // LayoutリソースのID
ViewGroup root // 親となる要素
)
LayoutInflater | Android Developers
ViewGroup viewGroup = (ViewGroup) findViewById(R.id.WidgetID); getLayoutInflater().inflate(R.layout.ResourceID, viewGroup);