在Android的Preference中,当在一个EditTextPreference中输入内容关闭之后,并不能实时看见输入的内容,这在有时候是很不方便,这是一个很常用的需求。实际上,可以通过如下的方法来实现。
public class AdvancedPreferences extends PreferenceActivity implements OnSharedPreferenceChangeListener { public static final String KEY_LIST_PREFERENCE = "list_preference"; public static final String KEY_CHECKBOX_PREFERENCE = "checkbox_preference"; private CheckBoxPreference mCheckBoxPreference; private ListPreference mListPreference; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Load the XML preferences file addPreferencesFromResource(R.xml.advanced_preferences); // Get a reference to the preferences mCheckBoxPreference = (CheckBoxPreference)getPreferenceScreen().findPreference(KEY_ADVANCED_CHECKBOX_PREFERENCE); mListPreference = (ListPreference)getPreferenceScreen().findPreference(KEY_LIST_PREFERENCE); } @Override protected void onResume() { super.onResume(); // Setup the initial values mCheckBoxPreference.setSummary(getPreferenceScreen().getSharedPreferences().getBoolean(key, false) ? "Disable this setting" : "Enable this setting"); mListPreference.setSummary("Current value is " + sharedPreferences.getValue(key, "")); // Set up a listener whenever a key changes getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); } @Override protected void onPause() { super.onPause(); // Unregister the listener whenever a key changes getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this); } public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { // Let's do something a preference value changes if (key.equals(KEY_CHECKBOX_PREFERENCE)) { mCheckBoxPreference.setSummary(sharedPreferences.getBoolean(key, false) ? "Disable this setting" : "Enable this setting"); } else if (key.equals(KEY_LIST_PREFERENCE)) { mListPreference.setSummary("Current value is " + sharedPreferences.getValue(key, "")); } }}
这样,当你变更了Preference的内容之后,就可以在Summary中看见内容了。