我們看到Android系統本身就大量用到了PreferenceActivity來對系統進行資訊配置和管理,那麼它是怎麼儲存資料的呢,如何建立PrefenceActivity的呢?
建立Android項目,並添加一個pref.xml檔案(先建一個xml名的Folder)。注意,這次選擇的不是Layout,而是Preference,而且注意Folder路徑是 res/xml.
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="General">
<CheckBoxPreference
android:key="checkbox1"
android:title="Using HTTP 1.1" />
<CheckBoxPreference
android:key="checkbox2"
android:title="Using Proxy" />
</PreferenceCategory>
<PreferenceCategory
android:title="Security">
<EditTextPreference
android:key="edittext_preference"
android:title="Setting Password"
android:dialogTitle="Please input password:"
android:password="true"/>
<ListPreference
android:key="list_preference"
android:title="Security Preferences"
android:entries="@array/list_preference"
android:entryValues="@array/list_preference"
android:dialogTitle="Security options" />
</PreferenceCategory>
<PreferenceCategory
android:title="Launch Submenu">
<PreferenceScreen
android:key="submenu"
android:title="Network tools">
<CheckBoxPreference
android:key="checkbox3"
android:title="Start fishing filter" />
<CheckBoxPreference
android:key="checkbox4"
android:title="Check website automatically"/>
</PreferenceScreen>
<PreferenceScreen
android:title="Launch Intent Activity">
<intent android:action="android.intent.action.VIEW"
android:data="http://www.google.com" />
</PreferenceScreen>
</PreferenceCategory>
</PreferenceScreen>
PreferenceCategory屬性分析:
title:顯示的標題
key:唯一標識(至少在同一程式中是唯一),SharedPreferences也將通過此Key值進行資料儲存,也可以通過key值擷取儲存的資訊 (以下相同)。
CheckBoxPreference屬性分析:
Key:唯一標識.
title:顯示標題(大字型顯示)
summary:副標題(小字型顯示)
defaultValue:預設值
EditTextPreperence屬性分析:
Key:唯一標識.
title:顯示標題(大字型顯示)
如何響應PreferenceActivity的操作。其實只要重寫PreferenceActivity的 onPreferenceTreeClick的方法就可以了
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.preference.PreferenceScreen;
public class PreferencesActivity extends PreferenceActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//設定視圖
addPreferencesFromResource(R.xml.preferences);
}
@Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen,
Preference preference) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String value = prefs.getString("edittext_preference", "unset");//通過key值取Value值
System.out.println("value-->"+value);
return false;
}
}