2

The following is guess work code for my PreferenceFragment it does not produce any errors but does not seem to be doing anything either :) the static xml version of this ListPreference is what is getting displayed. For the sake of simplifying the example below I am showing an array of strings "entries" and "entryValues" to populate the ListPreference but eventually those will be retrieved from my data model.

public class UserSettingsFragment : PreferenceFragment
{
    public override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        // Load the preferences from an XML resource
        AddPreferencesFromResource(Resource.Xml.UserSettings);

        // http://stackoverflow.com/questions/5375363/dynamic-listpreference-in-android
        //var lp = new ListPreference(Context);
        //var lp = FindViewById<ListPreference>(0);  // "prefSoundPack"
        // var lp = FindPreference("prefSoundPack").Context;
        var lp = new ListPreference(FindPreference("prefSoundPack").Context);
        lp.PreferenceClick += lp_PreferenceClick;
    }

    void lp_PreferenceClick(object sender, Preference.PreferenceClickEventArgs e)
    {
        var lp = new ListPreference(e.Preference.Context);
        String[] entries = { "Pack1", "Pack2" };
        String[] entryValues = { "0", "1" };
        lp.SetEntries(entries);
        lp.SetEntryValues(entryValues);
    }
}

My UserSettings.xml has something like

<PreferenceCategory android:title="@string/pref_Sound_settings">
    <ListPreference android:key="prefSoundPack"
                    android:title="@string/pref_SoundPacks_title"
                    android:summary="@string/pref_SoundPacks_summary"
                    android:defaultValue="1"
                    android:entries="@array/SoundPacks"
                    android:entryValues="@array/SoundPacksValues" >
    </ListPreference>
</PreferenceCategory>
Meryan
  • 1,285
  • 12
  • 25

1 Answers1

2

Since there's no answer; This should work from inside your OnCreate method:

ListPreference preference = (ListPreference) FindPreference("key");
preference.SetEntries(new String[] {"Pack 1", "Pack 2"});
preference.SetEntryValues(new String[] {"0", "1"});
rvanlaarhoven
  • 591
  • 6
  • 16