ListPreference相当于windows的下拉列表框,提供用户可选项和默认选项。要想在Android下定义一个这样的ListPreference,执行如下步骤:
1.创建一个描述选项的XML配置文件,在/res/xml/下定义对应的preference文件。例如:
<?xml version="1.0" encoding="utf-8"?> <!-- This file is /res/xml/flightoptions.xml --> <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" android:key="flight_option_preference" android:title="@string/prefTitle" android:summary="@string/prefSummary"> <ListPreference android:key="@string/selected_flight_sort_option" android:title="@string/listTitle" android:summary="@string/listSummary" android:entries="@array/flight_sort_options" android:entryValues="@array/flight_sort_options_values" android:dialogTitle="@string/dialogTitle" android:defaultValue="@string/flight_sort_option_default_value" /> </PreferenceScreen>
2.创建对应的现实和持有该Preference的Activity,该Activity扩展了android.preference.PreferenceActivity类,然后使用addPreferencesFromResource()添加资源。
public class FlightPreferenceActivity extends PreferenceActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.flightoptions); } }
下面是xml各属性项的解释:
属性 | 描述 |
android:key | 选项的字符串键值(你可以在程序中使用它指向选项) |
android:title | 选项标题 |
android:summary | 选项简短描述 |
android:entries | 列表中选项的字符串 |
android:entryValues | 定义每个选项的键值或值 |
android:dialogTitle | 对话框的标题(当视图作为模式对话框调用时显示) |
android:defaultValue | 默认列表值 |
下面需要定义对应的选项,值等内容:
<?xml version="1.0" encoding="utf-8"?> <!-- This file is /res/values/arrays.xml --> <resources> <string-array name="flight_sort_options"> <item>Total Cost</item> <item># of Stops</item> <item>Airline</item> </string-array> <string-array name="flight_sort_options_values"> <item>0</item> <item>1</item> <item>2</item> </string-array> </resources>
<?xml version="1.0" encoding="utf-8"?> <!-- This file is /res/values/strings.xml --> <resources> <string name="app_name">Preferences Demo</string> <string name="prefTitle">My Preferences</string> <string name="prefSummary">Set Flight Option Preferences</string> <string name="flight_sort_option_default_value">1</string> <string name="dialogTitle">Choose Flight Options</string> <string name="listSummary">Set Search Options</string> <string name="listTitle">Flight Options</string> <string name="selected_flight_sort_option">selected_flight_sort_option</string> <string name="menu_prefs_title">Settings</string> <string name="menu_quit_title">Quit</string> </resources>
通过调用函数Preference android.preference.PreferenceActivity.findPreference(CharSequence key);获取对应的选择框。例如
Preference selectFlightlist = findPreference(getString(R.string.selected_flight_sort_option));
比如更改selectFlightlist的概述,可用以下函数void android.preference.Preference.setSummary(CharSequence summary)
selectFightlist.setSummary("选择飞行列表");