34

Is it somehow possible to include one preferences.xml into another, like it can be done for layouts with the <include /> tag?

Let's say:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen 
    xmlns:android="http://schemas.android.com/apk/res/android">
    <PreferenceScreen 
        android:title="@string/pref_group_title_visual">
        <include 
            preferences_filename="xml/pref_visual"/>
    </PreferenceScreen>
...
GrAnd
  • 10,141
  • 3
  • 31
  • 43

4 Answers4

27

Solution here it is to inflate both preference files from PreferencesActivity. For example:

    addPreferencesFromResource(R.xml.options);
    addPreferencesFromResource(R.xml.additional_options);
soul
  • 331
  • 4
  • 3
  • This does, in fact, work. Perfectly. I added a little code snippet below that adds the ability for developers to display preferences that would only be available to the unsigned app pushed to the phone/emulator :) – Bill Mote May 08 '12 at 00:41
17

The solution soul shows works. It can be expanded to only show preferences if you're the developer using an unsigned version of the app ;)

addPreferencesFromResource(R.xml.options);
addPreferencesFromResource(R.xml.additional_options);
if (BuildConfig.DEBUG) {
    addPreferencesFromResource(R.xml.developer_options);
}

I created a blog post regarding this issue and have a complete working code example available for download. http://androidfu.blogspot.com/2012/05/developer-debug-with-nested-preferences.html

Bill Mote
  • 12,644
  • 7
  • 58
  • 82
4

To truly achieve the nesting effect you can use this technique to relocate the loaded preferences to a group already loaded.

PreferenceCategory notifications = (PreferenceCategory) getPreferenceScreen ().findPreference (PreferenceKey.pref_notifications.name ());
addPreferencesFromResource (R.xml.pref_notifications, notifications);

Where the enhanced addPreferencesFromResource is defined as:

private void addPreferencesFromResource (int id, PreferenceGroup newParent) {
    PreferenceScreen screen = getPreferenceScreen ();
    int last = screen.getPreferenceCount ();
    addPreferencesFromResource (id);
    while (screen.getPreferenceCount () > last) {
        Preference p = screen.getPreference (last);
        screen.removePreference (p); // decreases the preference count
        newParent.addPreference (p);
    }
}

It works for any PreferenceGroup such as PreferenceScreen and PreferenceCategory.

Eric Woodruff
  • 6,380
  • 3
  • 36
  • 33
2

No, it seems to be impossible. But there's a simple workaround. You can make another PreferenceActivity that loads nested PreferenceScreen. And in the main preference.xml file you need to create a Preference object and set an Intent object for it in code (using setIntent() method). This Intent must be used to create the second PreferenceActivity.

Michael
  • 53,859
  • 22
  • 133
  • 139