Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fill ListPreference dynamically from code?

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>
like image 403
Meryan Avatar asked Dec 19 '25 14:12

Meryan


1 Answers

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"});
like image 97
rvanlaarhoven Avatar answered Dec 22 '25 04:12

rvanlaarhoven



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!