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:summary="@string/first_default"
android:summaryOff="@string/first_off"
android:summaryOn="@string/first_on"
android:title="@string/first_title"
/>
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:summary="@string/first_default"
android:summaryOff="@string/first_off"
android:summaryOn="@string/first_on"
android:title="@string/first_title"
/>
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" >
< xml version="1.0" encoding="utf-8" >