Can Android Preferences/Settings screen be configu

2019-07-23 12:45发布

问题:

Android Tutorials and examples show how to use Preference Fragment and Preference Activity to create Settings screen in an app.

However, all preferences exposed this way get their values to 'DefaultSharedPreferences'.

What if we want to save preference values to other (non-default / custom) SharedPreferences.

The use case I have in mind is similar to email apps where an app may allow the user to create multiple accounts, and also give the user options to save settings for different accounts differently. One method that I see as an option would have been to 'programatially' add preference in the Preference screens, and specify a different Shared Preference target for each one of them (depending on account).

However, it seems that currently all preferences added to PreferenceFragment/Activity get their values saved to DefaultSharedPreferences.

Any pointers on this will be appreciated.

One

回答1:

Technically these three lines will get the job done from one side. And now that it sets the Preference for all the activities, the simple way to overcome that is it initialize default SharedPreferences where needed and Custom SharedPreferences where are wanted.

getPreferenceManager().setSharedPreferencesName("custom_prefs");
getPreferenceManager().setSharedPreferencesMode(MODE_PRIVATE);
addPreferencesFromResource(R.xml.prefs);