Sunday, January 31, 2010

How to populate a Spinner widget from an Array

Lets say we have an Array of colours, defined in a xml file in our res folder in our Eclipse project, like below.

<?xml version="1.0" encoding="utf-8"?>
<string name="hello">Hello World, droidTest1!</string>
<string name="app_name">droidTest1</string>

<string-array name="colours">

Spinners are Android's implementation of a dropdown menu, of sorts.
How do we insert these values into a spinner widget?

First, we need to create a layout for our Spinner widget, so it has a user interface.
We could do this is code, but the more accepted method is to define our layouts for Android applications in XML files, located in our res/layout folder in our project.







Then we create an instance of the Spinner class,

Spinner colourSpinner = (Spinner) findViewById(;

Next we create an ArrayAdapter to wrap our xml array (Array of colours) and we put some pre-defined styles.

ArrayAdapter adapter = ArrayAdapter.createFromResource( this, R.array.colors, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

And we set the ArrayAdapter to our instance of the Spinner class:

And when we run our application:

The closed Spinner Widget

.. When selected shows us out colour options.

Aaah.. Sweet Androidy Success!


1 comment:

  1. Would love to see this example posted like your SQL one was. Thanks!