【Androidアプリケーションの設定画面を作ろう】Preferenceのレイアウトを変更する
Preferenceはすべての設定項目の基礎となるクラスです。
そのため、このクラス自体を実際に使うことはありませんが、たくさんの重要な機能が定義されています。
Preferenceをxmlファイルのタグとして使い、属性を設定することで「見た目」・「プリファレンスとの連携」・「動き」を変更することができます。
Preferenceのレイアウトを変更する
Preferenceは下記のレイアウトファイルが使用されています。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?android:attr/listPreferredItemHeight"
android:gravity="center_vertical"
android:paddingEnd="?android:attr/scrollbarSize"
android:background="?android:attr/selectableItemBackground" >
<ImageView
android:id="@+android:id/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"/>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="15dip"
android:layout_marginEnd="6dip"
android:layout_marginTop="6dip"
android:layout_marginBottom="6dip"
android:layout_weight="1">
<TextView android:id="@+android:id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:textAppearance="?android:attr/textAppearanceLarge"
android:ellipsize="marquee"
android:fadingEdge="horizontal" />
<TextView android:id="@+android:id/summary"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@android:id/title"
android:layout_alignStart="@android:id/title"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="?android:attr/textColorSecondary"
android:maxLines="4" />
</RelativeLayout>
<!-- Preference should place its actual preference widget here. -->
<LinearLayout android:id="@+android:id/widget_frame"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:orientation="vertical" />
</LinearLayout>
上記のレイアウトファイルで十分な設定項目が作成できますが、Preferenceには自作のレイアウトファイルを読み込む属性が定義されています。
任意のレイアウトファイルを追記する
既存Viewに少しだけViewを追加する場合はandroid:widgetLayoutを設定します。この属性はレイアウトファイルリソースIDを設定できます。どのようなレイアウトファイルでも設定可能ですが、あまり表示領域が無いため複雑なViewを設定することはできません。
<Preference
android:title="widgetLayout"
android:widgetLayout="@layout/preference_widget_layout"/>
全てのレイアウトファイルを変更する
Preferenceが作り出すViewは全て変更することができます。
<Preference
android:title="layout"
android:layout="@layout/preference_layout" />