2012年1月29日日曜日

PreferenceActivityのレイアウトをカスタマイズ

PreferenceActivityにTextViewやButtonを配置したいときがあります。

(例)「国旗deクイズ」に於ける使用例



今回は、PreferenceActivityのレイアウトをカスタマイズする方法をまとめてみました。

PreferenceActivityクラスはListActivityを継承したクラスです。
必要に応じてリストにコンポーネントを設定することで設定画面を作成する仕様となっています。

リスト本体のレイアウトは、ListActivityクラスを継承したサブクラスを作成するときと同じす。
つまり、オーバーライドしたonCreate()メソッドの中でsetContentView()によって設定します。

以下はPreferenceActivityのデフォルト設定です。

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(com.android.internal.R.layout.preference_list_content);

mPreferenceManager = onCreatePreferenceManager();
getListView().setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
}

・XMLレイアウト(preference_list_content.xml)
<xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:drawSelectorOnTop="false"
android:scrollbarAlwaysDrawVerticalTrack="true"
/>

PreferenceActivityにTextViewやButtonを配置したいときは、
PreferenceActivityを継承したサブクラスでonCreate()をオーバーライドして、
用意したXMLレイアウトをsetContentView()に設定します。

以下はTextViewを一つ配置する例です。
コンポーネントはCheckBoxPreferenceを一つ設定します。

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(my_preference_list_content.xml);
addPreferencesFromResource(R.xml.settings);
}


・XMLレイアウト(my_preference_list_content.xml)
<xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="国旗deクイズ "/>
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</LinearLayout>


・XMLコンポーネント(setting.xml)
<xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference
android:key="setting"
android:title="データの保存"
android:summary="データの保存をONにする"
android:defaultValue="true" />
</PreferenceScreen>

0 件のコメント:

コメントを投稿