问题
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