ぷろぐらむおいしいよ

技術ネタを適当に書いていきます。

styleとincludeでレイアウトを綺麗にする

一つのXMLでレイアウトを書いていると、長くなったり重複している部分が出てきたりして大変なことになります。
そこで、style属性とタグを使ってXMLを綺麗にします。

style

styleを使うと複数のレイアウトに同じ属性を適応することが出来ます。


こんな感じのヘッダーを作ることを例にサンプルコードを示します。

style.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="text_style">
        <item name="android:layout_width">0dp</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:layout_weight">1</item>
        <item name="android:gravity">center</item>
        <item name="android:textColor">#FFFFFF</item>
        <item name="android:textSize">15sp</item>
    </style>

</resources>

header_with_style.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <TextView
        style="@style/text_style"
        android:background="#AA5500"
        android:text="piyo"/>

    <TextView
        style="@style/text_style"
        android:background="#AA0055"
        android:text="hoge"/>

    <TextView
        style="@style/text_style"
        android:background="#00AA55"
        android:text="fuga"/>

</LinearLayout>

このように、重複している要素をstyle.xmlにまとめることが出来ます。
ちなみにstyle.xmlはres/valuesのディレクトリに置きます。

include

includeを使うと別のXMLファイルのレイアウトを読み込むことが出来ます。

先ほどのheader_with_style.xmlを使って、

このようなレイアウトを作成します。

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <include
        android:id="@+id/header"
        layout="@layout/header_with_style" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#6666AA"
        android:text="ここにメインのコンテンツ"
        android:textColor="#000000"
        android:textSize="30sp"/>

</LinearLayout>

includeタグではandroid:id属性を上書きすることが可能です。*1

*1:android:layout_で始まる属性も上書き出来るらしいのですが、自分の環境では出来ませんでした