Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Mobile / Android

How to Populate a Spinner (Dropdown/Picklist) with Values in Android

4.29/5 (4 votes)
19 May 2014CPOL1 min read 63.2K  
Easily create and hook up values to display in an Android Spinner

Then Came Cervantes / Could It Be I'm Working My Way Back to La Mancha, Babe

To populate a Spinner (in other environments known as a dropdown or a picklist or so), follow these simple steps:

Open your project's arrays.xml file that should live below ...\app\src\main\res\values\

Add some items in a string-array section like so:

XML
<string-array name="quixote_characters">
    <item>Don Quixote</item>
    <item>Sancho Panza</item>
    <item>Teresa Panza</item>
    <item>Dulcinea del Toboso</item>
    <item>Rocinante</item>
    <item>Dapple</item>
    <item>Cide Hamete Benengeli</item>
    <item>Cardenio</item>
    <item>Mambrino's Helmet</item>
    <item>La Mancha</item>
</string-array>

...so that it looks like this:

Image 1

Add a Spinner to any Layout file (in Droidio (Android Studio), simply drag-and-drop a Spinner onto the image of the device to be emulated).

Alternatively, you can add the code directly by pasting in the following XML, and then modifying as necessary:

XML
<Spinner
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/spinnerQuixote" />

Then add this line to the XML:

XML
android:entries="@array/quixote_characters"

...to that Spinner's XML to hook the values added above to the Spinner. In context, that looks like this:

XML
<Spinner
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/quixoteSpinner"
        android:entries="@array/quixote_characters"
        android:layout_below="@+id/textView"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

...so that when you run it, it looks like so:

Image 2

An Embarrassment of Spoils

As a bonus, here is the code necessary to assign the selected value from the Spinner to a String variable:

Java
final Spinner spin = (Spinner) findViewById((R.id.quixoteSpinner));
final String spinVal = String.valueOf(spin.getSelectedItem());

Respect the Strength of My Mighty Arm!

If you like this tip, send me Mambrino's helmet, or at least a reasonable facsimile thereof (perhaps via clever usage of a 3D printer).

OR! You could purchase the Kindle edition (over 2,600 pages) in Spanish and English, paragraph-by-paragraph of Don Quixote.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)