PreferenceActivity/Settings with custom shared preferences as source

22 Views Asked by At

settings in android are stored in default shared preferences. This allows to have only one set of settins.

I would like to setup settings activity for multiple items. So my question is: Is it possible to tell Setting/PreferenceActivity to use named shared preferences instead of default shared preferences?

Thank you very much.

I was searching documentation of settigns in android. But I havent found any method to set source of Settings/PreferenceActivity

1

There are 1 best solutions below

0
Ahmad Reza Enshaee On

If you want to have specific preferences based on the specific app configurations that Android can handle already(like themes, locale, orientation, screen size, etc.), I believe you might be able to have different xml folders based on the specific configuration and load your keys from that file. It's worth mentioning that I haven't tested this approach and don't have any real evidence to support my recommendation.

Additionally, I don't know if we can specify different preference files that can work in parallel with Preference API, but one achievable thing is to have a preference that holds what type of preference you want to use and loads different values for preference keys based on that specific preference. Let's say for instance you want to have different preferences when the user is in different app themes(I'm using this example only for demonstration) and name it theme_mode which can hold an integer value of MODE_LIGHT, MODE_DARK, MODE_CONTRAST, etc.(these values are constants and can hold any integer values as long as they are different than each other). Then you can hold all of your setting keys and the functions for retrieving their values in a class named Settings. Then for each function that is fetching the value of that key, you can specify to return a different value based on the theme_mode preference. The same thing can happen for writing values. Keep in mind that this approach will make your settings fairly complicated but I believe if you couldn't find any way to specify the file name for the preferences, this might be a good option.