此类继承了Activity,用来在首选项设置中使用,和Activity一样,它需要一个资源文件,不过不是layout中的xml文件。在res中新建一个xml文件,在xml文件中新建一个Android xml file,如下图
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceCategory android:title="First Category" >
<ListPreference
android:key="list_key"
android:title="list title"
android:dialogTitle="list_dialog_title"
android:entries="@array/value_list_preference"
android:entryValues="@array/list_preference"
android:summary="list_summary" />
</PreferenceCategory>
<PreferenceCategory android:title="Second Category" >
<EditTextPreference
android:key="edittext_key"
android:summary="edit summary"
android:title="edit title" />
<CheckBoxPreference
android:key="checkbox_key"
android:summary="checkbox summary"
android:title="checkbox title" />
</PreferenceCategory>
</PreferenceScreen>
values中新建arrays.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="list_preference">
<item>Red</item>
<item>Blue</item>
<item>Green</item>
</string-array>
<string-array name="value_list_preference">
<item>红色</item>
<item>蓝色</item>
<item>绿色</item>
</string-array>
</resources>
Settings类:
public class Settings extends PreferenceActivity{
private EditTextPreference mEtPreference;
private ListPreference mListPreference;
private CheckBoxPreference mCheckPreference;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
//加载资源文件
addPreferencesFromResource(R.xml.preferencetest);
initPreferences();
}
private void initPreferences() {
// TODO Auto-generated method stub
mEtPreference = (EditTextPreference)findPreference("edittext_key");
mListPreference = (ListPreference)findPreference("list_key");
mCheckPreference = (CheckBoxPreference)findPreference("checkbox_key");
}
}
此时的界面应该是这样的:
PreferenceCategory是对Preference进行分类,key相当于id,title是显示的标题,summary是在title下的摘要,dialogtitle是弹出对话框的标题,entries是列表中显示的值,entryValues是列表中实际保存的值,与entries对应。
CheckBoxPreference:CheckBox选择项,对应的值的ture或flase
EditTextPreference:输入编辑框,值为String类型,会弹出对话框供输入。
ListPreference: 列表选择,弹出对话框供选择。
Preference:只进行文本显示,需要与其他进行组合使用。
首选项中选择的value会记录在SharedPreference中,SharedPreference中的key就是首选项的key。下面就是在MainActivity中进行验证,主界面设置了两个按钮,一个用来启动PreferenceActivity,另一个用来读取SharedPreference中存储的数据。
MainActivity:
public class MainActivity extends ActionBarActivity {
private Button btnSetting,btnShow;
private TextView tvCheckout,tvList,tvEditText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
btnSetting = (Button)findViewById(R.id.button1);
btnShow = (Button)findViewById(R.id.button2);
btnSetting.setOnClickListener(buttonListener);
btnShow.setOnClickListener(buttonListener);
tvCheckout = (TextView)findViewById(R.id.textView1);
tvList = (TextView)findViewById(R.id.textView2);
tvEditText = (TextView)findViewById(R.id.textView3);
}
private OnClickListener buttonListener = new OnClickListener() {
@Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.button1:
startActivity(new Intent(MainActivity.this,Settings.class));
break;
case R.id.button2:
showSettingInfo();
break;
}
}
};
private void showSettingInfo() {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
tvCheckout.setText(settings.getBoolean("checkbox_key", false)+"");
tvEditText.setText(settings.getString("edittext_key", ""));
tvList.setText(settings.getString("list_key", ""));
}
}
SharedPreferences的另一种获取方式:
SharedPreferences prefs = getSharedPreferences(“包名”, 0);
第二个参数是mode,缺省模式为MODE_PRIVATE
一开始的主界面:
我们选择bule,在edittext中输入123,选中checkbox
我们在进行选择之后,首选项的summary通常是要根据你所选的选项而变,我们可以让Settigns类实现OnSharedPreferenceChangeListener,在Settings中加入如下代码
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
// 得到首选项活动中的SharedPreferences
SharedPreferences sharedPreferences = getPreferenceScreen()
.getSharedPreferences();
mListPreference.setSummary(sharedPreferences.getString("list_key", ""));// 第二个参数表示如果没有值默认为空
sharedPreferences.registerOnSharedPreferenceChangeListener(this);
}
protected void onPause() {
super.onPause();
// Unregister the listener whenever a key changes
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,String key) {
// TODO Auto-generated method stub
if (key.equals("list_key")) {
mListPreference.setSummary(sharedPreferences
.getString(key, "white"));
}
}
此时你卸载程序之后在安装,listPreference的Summary就为空,这时你选择蓝色之后,summary就显示蓝色,不要忘了注册和解除监听器,这里的sharedPreferences都是局部变量。
以上的方法应该都被废弃了,仅供学习,自从Android 3.0引入fragment后,preference在实现有变化,下面是几个类的介绍。
PreferenceFragment用来show Preference的层次结构,他也要加载资源文件,Header中会有一个PreferenceFragment,当Header被选中,显示PreferenceFragment。
public class PreferenceWithHeaders extends PreferenceActivity {
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
if (hasHeaders()) {// 判断是否有Header
Button button = new Button(this);
button.setText("Some action");
setListFooter(button);// 在Footer加一个button
}
}
// 用top-level headers填充Activity
@SuppressLint("NewApi")
public void onBuildHeaders(List<Header> target) {
// 加载Headers所在的资源文件
loadHeadersFromResource(R.xml.headers, target);
}
@SuppressLint("NewApi")
public static class Prefs1Fragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.fragmented_preferences);
}
}
// 在Prefs1Fragment嵌套的一个PreferenceFragment
public static class Prefs1FragmentInner extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Can retrieve arguments from preference XML.
Log.i("args", "Arguments: " + getArguments());
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.inner);
}
}
/**
* This fragment shows the preferences for the second header.
*/
@SuppressLint("NewApi")
public static class Prefs2Fragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 从headers XML资源中检索参数
Log.i("args", "Arguments: " + getArguments());
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.dependencies);
}
}
}
当启动这个Activity时,判断是否有Header,如果有就在底部加一个按钮,Header是通过onBuildHeaders加载的,资源文件如下,注意其中的preference-headers是小写字母。这个类里还有几个内部类,用static修饰,header可以直接调用,fragment的资源文件中展示了PreferenceScreen的嵌套,也介绍了几种Preference的用法。
header.xml:
<?xml version="1.0" encoding="utf-8"?>
<preference-headers xmlns:android="http://schemas.android.com/apk/res/android" >
<!-- fragment 内部类 -->
<header
android:fragment="com.example.preferencedemo.PreferenceWithHeaders$Prefs1Fragment"
android:summary="An example of some preferences."
android:title="Prefs 1" />
<!-- 新增一个extra参数,用bundle传递 -->
<header
android:fragment="com.example.preferencedemo.PreferenceWithHeaders$Prefs2Fragment"
android:summary="Some other preferences you can see."
android:title="Prefs 2" >
<extra
android:name="someKey"
android:value="someHeaderValue" />
</header>
<!-- 用intent唤起活动 -->
<header
android:summary="Launches an Intent."
android:title="Intent" >
<intent
android:action="android.intent.action.VIEW"
android:data="http://www.baidu.com" />
</header>
</preference-headers>
fragmented_preferences.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceCategory
android:title="first_preferences">
<CheckBoxPreference
android:key="checkbox_preference"
android:title="checkbox_preference"
android:summary="可以选择" />
</PreferenceCategory>
<PreferenceCategory
android:title="second_preferences">
<EditTextPreference
android:key="edittext_preference"
android:title="edittext_preference"
android:summary="输入文本"
android:dialogTitle="dialog_title_edittext_preference" />
<ListPreference
android:key="list_preference"
android:title="list_preference"
android:summary="选择颜色"
android:entries="@array/list_preference"
android:entryValues="@array/value_list_preference"
android:dialogTitle="颜色列表" />
</PreferenceCategory>
<PreferenceCategory
android:title="launch_preferences">
<!-- This PreferenceScreen tag sends the user to a new fragment of
preferences. If running in a large screen, they can be embedded
inside of the overall preferences UI. -->
<PreferenceScreen
android:fragment="com.example.preferencedemo.PreferenceWithHeaders$Prefs1FragmentInner"
android:title="title_fragment"
android:summary="summary">
<!-- Arbitrary key/value pairs can be included for fragment arguments -->
<extra android:name="someKey" android:value="somePrefValue" />
</PreferenceScreen>
<!-- This PreferenceScreen tag sends the user to a completely different
activity, switching out of the current preferences UI. -->
<PreferenceScreen
android:title="title_intent_preference"
android:summary="summary">
<intent android:action="android.intent.action.VIEW"
android:data="http://www.baidu.com" />
</PreferenceScreen>
</PreferenceCategory>
<PreferenceCategory
android:title="preference_attributes">
<CheckBoxPreference
android:key="parent_checkbox_preference"
android:title="title_parent_preference"
android:summary="summary_parent_preference" />
<!-- The visual style of a child is defined by this styled theme attribute. -->
<CheckBoxPreference
android:key="child_checkbox_preference"
android:dependency="parent_checkbox_preference"
android:layout="?android:attr/preferenceLayoutChild"
android:title="title_child_preference"
android:summary="summary_child_preference" />
</PreferenceCategory>
</PreferenceScreen>
inner.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<CheckBoxPreference
android:key="checkbox"
android:summary="内置的fragment"
android:title="inner" />
</PreferenceScreen>
dependencies.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
android:title="Preferences">
<PreferenceScreen android:key="pref"
android:title="title_screen"
android:summary="summary">
<CheckBoxPreference android:key="checkbox1"
android:title="title1"
android:summaryOn="show summary"
android:summaryOff="not show summary" />
<CheckBoxPreference
android:key="checkbox2"
android:title="title2"
android:summary="summary2" />
<CheckBoxPreference
android:key="checkbox3"
android:title="title3"
android:summary="summary3" />
</PreferenceScreen>
<PreferenceScreen android:key="key_screen"
android:title="title_screen">
<EditTextPreference android:key="edittext"
android:title="title_edittext"
android:summary="summary_edittext"
android:dialogTitle="title_dialog" />
</PreferenceScreen>
<PreferenceScreen android:key="ringtone"
android:title="Ring Tones"
android:summary="Set Ring Tones ">
<RingtonePreference android:key="ringtone_pre"
android:title="title_ringtone"
android:summary="summary_ringtone"
android:showSilent="true"
android:ringtoneType="ringtone"/>
</PreferenceScreen>
</PreferenceScreen>
点击第二个header:
代码链接:http://download.csdn.net/detail/tomi_en/9491992