Search code examples
androidandroid-preferencesandroid-2.3-gingerbread

Can I use a single settings.xml <PreferenceScreen> element in different places, with dynamically-generated keys?


First of all, I'm using API Level 10, so I need solutions that use the older, deprecated APIs for preferences.

I have a <PreferenceScreen> defined in a settings.xml as follows (there are more preferences, but I have included just one for sake of illustration:

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
  <CheckBoxPreference 
    android:key="@string/key_pref_match_locality" 
    android:defaultValue="false"
    android:title="@string/title_pref_match_locality"
    android:summary="@string/summary_pref_match_locality" />
</PreferenceScreen>

Now the way I want my app to be structured is to use this preference screen in multiple places. How? Imagine this scenario:

  1. I have a list of people, assigned to various groups. Take, for example, "Friends", "Family", "Colleagues".
  2. I want to have a set of preferences associated with a "default" group, and with each individual group. In all, for this example, I'll have 4 sets of preferences -- Default, Friends, Family, Colleagues -- which I will consequently upload on a server.

Ideally, I want the key of a preference to indicate which kind of preference it is. So for the default group's preference, I want the key of a preference to be "DEFAULT_pref_match_locality", and for group "Friends", it should be "GROUP_Family_pref_match_locality".

Is there a way I can use a single <PreferenceScreen> defined in settings.xml and dynamically create multiple screen instances which all use different keys?


Solution

  • Yes, you can. Just load the PreferenceScreen everywhere you need to, inflate the Preference elements and change their keys dynamically using the Preference.setKey() method. This should work.