レイアウトファイルを分割する

AndroidのUIを記述するにはxmlでレイアウトファイルを記述しなくてはいけない。
eclipseプラグインに、いちおうWYSIWYGエディタも付いているが、使い勝手が悪いし、xmlエディタもタグの折りたたみなどをサポートしていないためちょっと複雑なものになると行数がどんどん増え、メンテナンスしづらくなってしまう。

そんなときはincludeを使ってファイルを分割しましょう。

使用例

Tabを使う場合、FrameLayoutの子要素に切り替える画面を保持するが、WYSIWYGエディタでは一番上位にある画面しか表示することが出来ない。
下記の用にincludeを使ってTabで切り替わる画面を別ファイルにしておけば、WYSIWYGエディタを使うこともできるし、構造もわかりやすくなる。

<FrameLayout android:id="@android:id/tabcontent" android:layout_width="fill_parent" android:layout_height="fill_parent">
	<LinearLayout android:id="@+id/tab1" android:layout_width="fill_parent" android:layout_height="fill_parent">
		<include android:id="@+id/cell1" layout="@layout/tab_content_1" />	</LinearLayout>
	<LinearLayout android:id="@+id/tab2" android:layout_width="fill_parent" android:layout_height="fill_parent">
		<include android:id="@+id/cell1" layout="@layout/tab_content_1" />
	</LinearLayout>
</FrameLayout>

また、include時にidを個別に割り振れるので共通部品を別ファイルにしておいて、個別のIDを持たせて使うこともできる。

 <include android:id="@+id/cell1" layout="@layout/workspace_screen" />
    <include android:id="@+id/cell2" layout="@layout/workspace_screen" />
    <include android:id="@+id/cell3" layout="@layout/workspace_screen" />

これで可読性、メンテナンス性を向上させることができそうだ。

参考