I've implemented my own PreferenceFragment subclass (detailed here), and want to listen for preference changes within it. PreferenceFragment provides you with two ways of doing this:
getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
and
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
Which one should be used? What's the difference? I don't really understand the distinction made in the Android docs.
PreferenceScreen see domentation here
PreferenceScreen class can appear in two places:
PreferenceManager see documentation here:
Difference :
getPreferenceManager ()
returns the current preference manager associated with the fragment.getPreferenceScreen ()
returns the rootPreferenceScreen
i.e. root preference screen used in the fragment from preference xml file(preferences.xml).The core difference is in their names,
PreferenceManger
grants access to different functionalities to the developer for managingSharedPreferences
, such as retrieving the map of current preference values or setting user preferences. to their default values.PreferenceScreen
handles displaying a screen of user preferences, so that the user can assign values to them. Sometimes this means displaying a list item on a screen with other preferences, that opens another screen with more preferences when clicked, as is the case whenPreferenceScreen
s are nested.Your question implies that you think there is a difference between what
PreferenceManager.getSharedPreferences()
andPreferenceScreen.getSharedPreferences()
does, but according to the source code, they are identical.PreferenceScreen
:So the
PreferenceManger
andPreferenceScreen
are different entities, but theSharedPreference
those method return should be the same object, sincePreferenceScreen
calls the method fromPreferenceManager
. I hope that is the answer you've been seeking.If you have a choice, go with
PreferenceManager.getSharedPreferences()
, it's more obvious and one fewer method call internally.Fun fact:
PreferenceFragment
:The first one gets the shared preferences from the
PreferenceManager
. The second one, from thePreferenceScreen
, that inherits this method fromPreference
class.I think this is not a functional difference, because both return probably the same instance of the
SharedPreferences
objects, but I think it's clearer to use the first one (usingPreferenceManager
instead ofPreferenceScreen
).