レイアウトの再利用
複数のレイアウトファイルで同じような配置がいくつもでてくる場合
その都度コードをコピペするとコード量が無駄に多くなる
この場合、共通する部分はレイアウトファイルを1つ作成して
includeで呼び出せば無駄が省ける
まずほ、再利用するレイアウトファイルを作成
ファイル名はinclude.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | < LinearLayout android:layout_width = "match_parent" android:layout_height = "wrap_content" android:orientation = "horizontal" > < TextView android:layout_width = "0dp" android:layout_height = "@dimen/layout_common_size_xlarge" android:layout_weight = "1" android:background = "@color/FlatLightCyan" android:gravity = "center" android:text = "再利用テスト" android:textColor = "@android:color/white" /> < TextView android:layout_width = "0dp" android:layout_height = "@dimen/layout_common_size_xlarge" android:layout_weight = "1" android:background = "@color/FlatLightYellow" android:gravity = "center" android:text = "再利用テストその2" android:textColor = "@color/white" /> < TextView android:layout_width = "0dp" android:layout_height = "@dimen/layout_common_size_xlarge" android:layout_weight = "1" android:background = "@color/FlatLightRed" android:gravity = "center" android:text = "再利用テストその3" android:textColor = "@android:color/white" /> </ LinearLayout > |
これで、共通部分はできたので
次に個別のパーツ作成
このあたりはPHPとかでwordpressのテンプレートとかいじった経験あるとわかりやすい
これで、レイアウトファイルをincludeすると
再利用したいレイアウトファイルを任意の場所へ読み込める
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | < LinearLayout android:layout_width = "match_parent" android:layout_height = "match_parent" android:orientation = "vertical" > < TextView android:layout_width = "match_parent" android:layout_height = "wrap_content" android:layout_marginBottom = "@dimen/padding_small" android:layout_marginTop = "@dimen/padding_xlarge" android:text = "もともとのレイアウトファイル" > < include layout = "@layout/include" /> </ LinearLayout > |
これで、レイアウトファイルが組み込まれるようになる