Search code examples
androidandroid-activitysharedpreferencespreferences

add specific named SharedPreferences from resource in PreferenceActivity or PreferenceFragment


If I have a Preference-Activity or -Fragment I can provide a preference.xml file to build my PreferenceScreen and show it via addPreferenceFromResource(R.xml.preference)

Changed values can then be retrieved by PreferenceManager.getDefaultSharedPreferences(Context)

I'm just wondering if it is possible to take other than the default Preferences for my Fragment.

I want to have a PreferenceFragment that is able to store its Preferences (provided via xml) in Preferences I can retrieve via context.getSharedPreferences("customPrefName", Context.MODE_PRIVATE) but I couldn't find something in the xml like

<PreferenceScreen android:prefName="customPrefName">...

Solution

  • If you want to have a custom preference xml file, you need to set preference name before adding it to screen from xml in your PreferenceFragment class.

    public class CustomNamePreferenceFragment extends PreferenceFragment {
    
        private static final String PREF_FILE_NAME = "custom_name_xml";
    
        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            PreferenceManager preferenceManager = getPreferenceManager();
            preferenceManager.setSharedPreferencesName(PREF_FILE_NAME);
            addPreferencesFromResource(R.xml.prefs);
            ... //rest of the code
        }
    }
    

    Note : You need to set shared preference name just after the super call of onCreate() and before calling addPreferencesFromResource() method.