setPreferencesFromResource vs addPreferencesFromResource

Viewed 1209

This question is more academic than procedural. My preference screen displays and works fine, but while looking up various examples of the proper implementation of AppCompatPreferenceActivity, I discovered people handle loading the XML setting's resource differently in their sample code.

I am only using a single, simple settings setup, all within a single PreferenceScreen and category, but PreferenceFragmentCompat seems to still be the most appropriate and versatile way to go, leaving more options open for the future. I may or may not add more settings and or categories later.

My question is just this, given the parameters above, are there any benefits or disadvantages in using one call over the other (setPreferencesFromResource vs addPreferencesFromResource).

I've have tried both:

public class PreferenceFragmentCustom extends PreferenceFragmentCompat
{
  @Override
  public void onCreatePreferences(Bundle savedInstanceState, String rootKey)
  {    
    setPreferencesFromResource(R.xml.app_preferences, rootKey);
  }
}

and

public class PreferenceFragmentCustom extends PreferenceFragmentCompat
{
  @Override
  public void onCreatePreferences(Bundle savedInstanceState, String rootKey)
  {
    addPreferencesFromResource(R.xml.app_preferences);
  }
}

but, they both seem to work the same (remember, I am not swapping different preference fragments in and out and may or may not in the future).

Again, given the circumstances cited above, I'm asking if there is any reason to choose one method of loading the XML setting's resource over the other (setPreferencesFromResource vs addPreferencesFromResource).

Thank you in advance.

1 Answers

they do different things, look at the docs

addPreferencesFromResource : Inflates the given XML resource and adds the preference hierarchy to the current preference hierarchy.

setPreferencesFromResource: Inflates the given XML resource and replaces the current preference hierarchy (if any) with the preference hierarchy rooted at key.

so basically if you have an app where you want the user to see changed preferences after he does something or even changes a setting then you should use setPreferences to achieve the change.

if your app is big and there are various functionalities each with their own settings then addPreferences can help you in not having to write the entire preference xml at once but rather let it grow organically each functionality having its own preference xml fragment

these are just two examples where the distinctions between the functionality of these two methods might come in handy but I am sure there are many more.

If in your case you dont really care and you only have one preference fragment I guess it really does not matter. tchnically I guess setPreferences would be the "more correct" one but both methods are part of the same library and, as you said, to some extent their functionality overlaps so who cares XD

Related