Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
219 views
in Technique[技术] by (71.8m points)

android - PreferenceFragment - Difference between getPreferenceManager() and getPreferenceScreen()?

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.

question from:https://stackoverflow.com/questions/13618335/preferencefragment-difference-between-getpreferencemanager-and-getpreference

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The core difference is in their names, PreferenceManger grants access to different functionalities to the developer for managing SharedPreferences, 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 when PreferenceScreens are nested.

Your question implies that you think there is a difference between what PreferenceManager.getSharedPreferences() and PreferenceScreen.getSharedPreferences() does, but according to the source code, they are identical.

PreferenceScreen:

public SharedPreferences getSharedPreferences() {
     if (mPreferenceManager == null) {
         return null;
     }

     return mPreferenceManager.getSharedPreferences();
 }

So the PreferenceManger and PreferenceScreen are different entities, but the SharedPreference those method return should be the same object, since PreferenceScreen calls the method from PreferenceManager. 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:

public PreferenceManager getPreferenceManager() {
    return mPreferenceManager;
}

public PreferenceScreen getPreferenceScreen() {
    return mPreferenceManager.getPreferenceScreen();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...