我們看到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:顯示標題(大字體顯示)
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;
}
}