I'm creating lists in a shared preference and when the onPreferenceChanged() method is called I want to extract the index of the item in the list or an integer value in some cases. I am trying to build the xml data as follows:
in the arrays:
<string-array name="BackgroundChoices">
<item>Dark Background</item>
<item>Light Background</item>
</string-array>
<array name="BackgroundValues">
<item>1</item>
<item>0</item>
</array>
<string-array name="SpeedChoices">
<item>Slow</item>
<item>Medium</item>
<item>Fast</item>
</string-array>
<array name="SpeedValues">
<item>1</item>
<item>4</item>
<item>16</item>
</array>
in the preferences xml file:
<PreferenceScreen android:key="Settings"
xmlns:android="http://schemas.android.com/apk/res/android"
android:title="Settings">
<ListPreference
android:key="keyBackground"
android:entries="@array/BackgroundChoices"
android:summary="Select a light or dark background."
android:title="Light or Dark Background"
android:positiveButtonText="Okay"
android:entryValues="@array/BackgroundValues"/>
<ListPreference
android:key="keySpeed"
android:entries="@array/SpeedChoices"
android:summary="Select animation speed."
android:title="Speed" android:entryValues="@array/SpeedValues"/>
</PreferenceScreen>
So my xml does not work. I know how to do this using a string-array rather than an array for the values. And I could pull out the value strings and derive what I want from that but I would rather (if possible) be able to have lists where the values were ints, booleans, or enums. What is the customary way to do this?
thanks in advance,
Jay
Put the preferences in as
String
and useInteger.parseInt()
. I think there is actually a bug report on the limitation you are referring to but I can't find the link. From experience I can tell you to just useStrings
and save your self a lot of frustration.Note to other SO users, if you can prove me wrong, I welcome it.
Here's a
ListIntegerPreference
class I use (written forcom.android.support:preference-v7:24.0.0
). It overwrites a few methods and converts betweenInteger
andString
where possible, so that the baseListPreference
does not recognise, that you are working withIntegers
instead ofStrings
.I'm using this with creating
ListPreferences
values via code, just try it. It may work right away, or maybe you need to override additional functions. If so, this is a good start and shows you how you can do it...Based on the Android's ListPreference, I created IntListPreference. The usage is straighforward - simply put this snippet in your preferences xml:
and that in strings.xml
Andrew was correct, the thread is here:
it's still being commented on, and yet no change (as of 2.3.3 anyway).
Integer.parseInt() of .valueOf() will have to work. If valueOf() works without error, use it, as it doesn't allocate as much as parseInt() does, helpful when you NEED to avoid GC like I do.