android.preference.ListPreference的一些特性
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/xml/flightoptions.xml -->
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
android:key="flight_option_preference"
android:title="@string/prefTile"
android:summary="@string/prefSummary">
<ListPreference
android:key="@string/selected_flight_sort_option" //选项的名称或键
android:title="@string/listTitle" //选项的标题
android:summary="@string/listSummery" //选项的简短摘要
android:entries="@array/flight_sort_options" //可将选项设置成的列表项文本
android:entryValues="@array/flight_sort_options_values" // 定义每个列表项的键或值
android:dialogTitle="@string/dialogTile" // 对话框的标题
android:defaultValue="@string/flight_sort_option_default_value"/> //项列表中选项的默认值
</PreferenceScreen>
第二步:加载布局
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//加载上面的布局flightoptions.xml
addPreferencesFromResource(R.xml.flightoptions);
PreferenceManager manager=getPreferenceManager();
ListPreference listPreference=(ListPreference)manager.findPreference("selected_flight_sort_option");
}
第三步:编写列表项数组
<?xml version="1.0" encoding="utf-8"?>
<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>3</item>
</string-array>
</resources>
第四步:标题
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">FirstListPreference Demo</string>
<string name="menu_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="prefTile">My Preferences</string>
<string name="prefSummary">Set flight option preferences</string>
<string name="selected_flight_sort_option">selected_flight_sort_option</string>
<string name="listTitle">Flight option</string>
<string name="listSummery">Set search options</string>
<string name="dialogTile">Choose Flight Options</string>
<string name="flight_sort_option_default_value">1</string>
</resources>