Search code examples
androidsharedpreferencesandroid-preferences

Android SharedPreferences: How to define keys at runtime?


The Android documentation describes how to create a "preferences" UI using either a PreferenceActivity or a PreferenceFragment. The preferences themselves are defined in a XML file (e.g. preferences.xml) which contain, among other things, the "key" (android:key) to use to store each preference in the app's SharedPreferences.

This is good for apps which have a single set of preferences. However let's assume that there is an app that can have multiple "items" (for example: multiple account in a video chat app), and needs to show a preferences screen for each account.

How can this be done? Is it possible to specify the keys at runtime (so that e.g a different prefix can be used for each account)? Is there a better way to approach this?


Solution

  • Yes, its possible! you can assign keys on Runtime like, but as you said in comments that you need to change the Keys of the pre-defined Preferences in Xml rather than creating new Preferences explicitly, here's a method -

    Preference pref = findPreference("my_pref");
    String myPrefix = "prefix_";
    pref.setKey(myPrefix + pref.getKey());