PreferenceActivity使用示例 (三)

2014-11-24 10:36:23 · 作者: · 浏览: 2
*/
private class PreferenceChangeListenerImpl implements OnPreferenceChangeListener{
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
String preferenceKey=preference.getKey().toString();
if (preferenceKey.equals(getResources().getString(R.string.first_key))) {
System.out.println("切换后值为:"+newValue.toString());
}
if (preferenceKey.equals(getResources().getString(R.string.listpreference_key))) {
System.out.println("切换后值为:"+newValue.toString());
}
return true;
}

}

@Override
public void onBackPressed() {
getValuesFromSP();
super.onBackPressed();
}

// 从PreferenceActivity的SharedPreferences中取数据
private void getValuesFromSP(){
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
Boolean first_value = sp.getBoolean(getResources().getString(R.string.first_key), false);
String listpreference_key = sp.getString(getResources().getString(R.string.listpreference_key), null);
System.out.println("从SharedPreferences中取出的是:" + first_value);
System.out.println("从SharedPreferences中取出的是:" + listpreference_key);
}
}
preferenceactivity.xml如下:

[html]
< xml version="1.0" encoding="utf-8" >


android:key="@string/first_key"
android:summary="@string/first_default"
android:summaryOff="@string/first_off"
android:summaryOn="@string/first_on"
android:title="@string/first_title"
/>

android:dialogIcon="@drawable/ic_launcher"
android:dialogTitle="@string/listpreference_title"
android:entries="@array/names_array"
android:entryValues="@array/values_array"
android:key="@string/listpreference_key"
android:negativeButtonText="@string/listpreference_no"
android:summary="@string/listpreference_summary"
android:title="@string/listpreference_title"
android:defaultValue="222"
/>

< xml version="1.0" encoding="utf-8" >

android:key="@string/first_key"
android:summary="@string/first_default"
android:summaryOff="@string/first_off"
android:summaryOn="@string/first_on"
android:title="@string/first_title"
/>

android:dialogIcon="@drawable/ic_launcher"
android:dialogTitle="@string/listpreference_title"
android:entries="@array/names_array"
android:entryValues="@array/values_array"
android:key="@string/listpreference_key"
android:negativeButtonText="@string/listpreference_no"
android:summary="@string/listpreference_summary"
android:title="@string/listpreference_title"
android:defaultValue="222"
/>

strings.xml如下:

[html]
< xml version="1.0" encoding="utf-8" >


TestPreferenceActivity
Settings
Hello world!

first_key
first_on
first_off
first_title
first_default

listpreference_key
listpreference_title
listpreference_summary
listpreference_message
OK
NO

< xml version="1.0" encoding="utf-8" >

TestPreferenceActivity
Settings
Hello world!

first_key
first_on
first_off
first_title
first_default

listpreference_key
listpreference_title
listpreference_summary
listpreference_message
OK
NO