摘自:Pro Android2
在res/xml目录下的XML文件中定义首选项。要向用户显示首选项,编写一个活动类来扩展预定义的Android类android.preference.PreferenceActivity,然后使用addPreferencesFromResource(R.xml.flightoptions);将资源添加到活动的资源集合中。该框架会负责剩余操作(显示和持久化)。
项目结构:
项目源码:
1、首选项XML文件和相关的活动类:
flightoptions.xml:
<?xml version="1.0" encoding="utf-8"?> <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>
FlightPreferenceActivity.java:
package com.wl;
import com.wl.R;
import android.os.Bundle;
import android.preference.PreferenceActivity;
public class FlightPreferenceActivity extends PreferenceActivity{
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.flightoptions);
}
}
2、项目上的其他部分:
arrays.xml:
<?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>2</item> </string-array> </resources>
strings.xml:
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="hello">Hello World, MainActivity!</string> <string name="app_name">Perference 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_pref_title">Settings</string> <string name="menu_quit_title">Quit</string> </resources>
mainmenu.xml:
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" > <group android:id="@+id/menu_testPick"> <item android:id="@+id/menu_prefs" android:title="@string/menu_pref_title"/> <item android:id="@+id/menu_quit" android:title="@string/menu_quit_title"/> </group> </menu>
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" > <TextView android:id="@+id/text1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="" /> </LinearLayout>
MainActivity.java:
package com.wl; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.TextView; public class MainActivity extends Activity { private TextView tv = null; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); this.tv = (TextView)this.findViewById(R.id.text1); setOptionText(); } //创建options菜单,需要按手机上的menu键才会触发这个方法 @Override public boolean onCreateOptionsMenu(Menu menu){ MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.mainmenu, menu); return super.onCreateOptionsMenu(menu); } //选择options菜单中的一个option触发方法 @Override public boolean onOptionsItemSelected(MenuItem item){ if(item.getItemId() == R.id.menu_prefs){ Intent intent = new Intent().setClass(this, FlightPreferenceActivity.class); this.startActivityForResult(intent, 0); } else if(item.getItemId() == R.id.menu_quit){ finish(); } return super.onOptionsItemSelected(item); } //当从首选项视图回退到主视图(this activity)时触发。 public void onActivityResult(int reqCode, int resCode, Intent data){ super.onActivityResult(reqCode, resCode, data); setOptionText(); } private void setOptionText(){ SharedPreferences prefs = getSharedPreferences("com.wl_preferences", 0); String option = prefs.getString(this.getResources().getString(R.string.selected_flight_sort_option), this.getResources().getString(R.string.flight_sort_option_default_value)); String[] optionText = this.getResources().getStringArray(R.array.flight_sort_options); tv.setText("option value is " + option + " (" + optionText[Integer.parseInt(option)] + ")"); } }
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.wl" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="7" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <activity android:name=".MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".FlightPreferenceActivity" android:label="@string/prefTitle"> <intent-filter> <action android:name="com.syh.intent.action.FlightPreferences"/> <category android:name="android.intent.category.PEFERENCE"/> </intent-filter> </activity> </application> </manifest>
在完成更改并运行此应用程序之后,首先会看到一个简单的文本信息,显示“option value is 1(# of Stops)”。单击Menu按钮,然后在Settings上找到PreferenceActivity。完成之后,单击向后按钮,将会立即看到对选项文本所做的任何修改。
android框架负责持久化首选项。例如,当用户选择一个排序选项时,Android会将选择存储在应用程序/data目录下的一个XML文件中。实际的文件路径为/data/data/[PACKAGE_NAM]/shared_prefs/[PACKAGE_NAME]_preferences.xml。本示例的com.wl_preferences.xml文件内容是:
<?xml version='1.0' encoding='utf-8' standalone='yes' ?> <map> <string name="selected_flight_sort_option">1</string> </map>
可以看到,首选项都是通过其key特性来保存的。
如果拥有多个首选项,可以构建一个试图来显示首选项高级类别。用户然后可以深入到每个类别,查看和管理特定于该组的首选项。可以在根PreferenceScreen中引入嵌套的PreferenceScreen元素来实现此目标。