I have a problem with spinner in android, I cant set enum values to its content. Here is code of spinner :
<Spinner
android:id="@+id/spTrainingType"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:entries="@attr/TrainingType"
android:prompt="@string/hint_training_type" />
And here is enum :
<declare-styleable name="TrainingStyle">
<attr name="RecallType">
<enum name="Vibro" value="1" />
<enum name="Music" value="2" />
<enum name="Silent" value="3" />
<enum name="Alarm" value="4" />
</attr>
<attr name="RepeatType">
<enum name="Daily" value="1" />
<enum name="Weekly" value="2" />
<enum name="Monthly" value="3" />
</attr>
<attr name="TrainingType">
<enum name="Jogging" value="1" />
<enum name="Cross" value="2" />
<enum name="Climbing" value="3" />
<enum name="BikeTrip" value="4" />
</attr>
</declare-styleable>
So is there any way to put enums to spinner, or only arrays? Or may be i’m doing smth wrong.
Thanks in advance.
As far as I know, what you’re trying to do isn’t possible in its current form. The
attrnamespace is meant to house ‘attributes’ forView(Group)s/Widgets etc, not values – hence the abbreviation. If you think about it for a second, if this were supported, there probably would’ve been something like agetEnumeration()method in theResourcesclass, or potentially a more generic version for mapping values into a… well,Map.The standard approach to making key/value pairs work with a
Spinner, is to define separate arrays for the keys and values inres/values/arrays.xml. Items in such an array are loaded in-order, so you can use index-based lookups to match keys against values (and vice versa).An alternative approach, which I’m sure you’ll find suggested if you search around a little bit, is to merge the key and value into a single string; e.g. by using a special delimiter character, but this probably means you’ll need to pre-process it before displaying it to the user. It’s not the most flexible solution and definitely not what I’d prefer.
That being said, it’s not too hard to implement your own
XmlPullParserto load key/value pairs from a resource/xml file. If you follow that link to the class documentation, you’ll actually find a very basic implementation given for free. 🙂