PreferenceActivity是什么?
我们看到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;
}
}
posted on 2011-07-18 22:36 android开发实例 阅读(4156) 评论(0) 编辑 收藏 举报