Android adding item to list preference programaticly

核能气质少年 提交于 2019-12-11 18:34:26

问题


I feel like i have been searching every where without finding an answer to this.

I have a list preference

     <ListPreference
            android:key="signedUpCompetetion"
            android:entries="@array/listArray"
             android:entryValues="@array/listValues"
                />

With the following entries and entryValues:

    <resources>
<string-array name="listArray">
    <item></item>
    <item></item>
    <item></item>
</string-array>
<string-array name="listValues">
    <item></item>
    <item></item>
    <item></item>
</string-array>
</resources>

So say that in one of my activities i want to add something to the list.

The following is an attempt but it doesnt seem to work:

this.appPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
this.prefEditor = appPrefs.edit();
ListPreference list = (ListPreference) getSharedPreferences("signedUpCompetetion", MODE_PRIVATE);
list.setEntries("This is a test");

Anyone able to tell me how to add to a listpreference?

Update By the looks of it this seems to work

        PreferenceScreen root = this.getPreferenceScreen();
    ListPreference list = (ListPreference) root.findPreference("signedUpCompetetion");
    CharSequence[] entries = { "One", "Two", "Three" };
    CharSequence[] entryValues = { "1", "2", "3" };
    list.setEntries(entries);
    list.setEntryValues(entryValues);

However there is 1 problem! if i restart the application the list is not preserved. which means that the list is empty!


回答1:


Use setEntries(int) and setEntryValues(int)

    list.setEntries(R.array.listArray);
    list.setEntryValues(R.array.listValues);

Update for how to persist the data:

You can persist the data in several ways, the simplest one would be to call setPersistent(true):

    list.setPersistent(true);


来源:https://stackoverflow.com/questions/16754428/android-adding-item-to-list-preference-programaticly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!