I want to use any SharedPreferences in PreferenceFragment

Asked 2 years ago, Updated 2 years ago, 32 views

PreferenceFragment is easy to create a configuration screen, but it assumes that you use the default SharedPreferences and can only edit global settings in the app.

Would it be possible to link any SharedPreferences by name to the PreferenceFragment screen?The original purpose is to easily implement the App Widgets instance-specific configuration screen.

android

2022-09-30 16:27

2 Answers

Before calling addPreferencesFromResource(R.xml.preferences) in the PreferenceFragment onCreate, you can specify the name of the SharedPreferences to use by using getPreferenceManager().setSharedPreferencesName.


2022-09-30 16:27

getPreferenceManager().setSharedPreferencesName(name)?See you.

Do you mean PreferenceManager#getDefaultSharedPreferences when you say getDefaultSharedPreferences on which PreferenceFragment depends?

Once you have set the name in PreferenceManager#setSharedPreferencesName, do not use PreferenceManager#getDefaultSharedPreferences, but use the name you set in PreferenceManager#getSharedPreferences or Context#getSharedPreferences

The SharedPreferences name returned by PreferenceManager#getDefaultSharedPreferences is hardcoded with "package name +_preferences" as far as the source code goes, so it is unlikely to be changed.


2022-09-30 16:27

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.