Wednesday, January 5, 2011

How to populate a Spinner widget from an Array

By Magesh Kumar   Posted at  2:00 AM   Android No comments

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


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

<string-array name="colours">
<item>Red</item>
<item>Blue</item>
<item>White</item>
<item>Yellow</item>
<item>Black</item>
<item>Green</item>
<item>Purple</item>
<item>Orange</item>
<item>Grey</item>
</string-array>
</resources>
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.

<Spinner

android:id="@+id/my_colour_spinner"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:drawSelectorOnTop="true”

/>


Then we create an instance of the Spinner class,

Spinner colourSpinner = (Spinner) findViewById(R.id.my_colour_spinner);



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:
colourSpinner.setAdapter(adapter);


And when we run our application:

The closed Spinner Widget



.. When selected shows us out colour options.



About the Author

Nulla sagittis convallis arcu. Sed sed nunc. Curabitur consequat. Quisque metus enim, venenatis fermentum, mollis in, porta et, nibh. Duis vulputate elit in elit. Mauris dictum libero id justo.
View all posts by: BT9

0 comments:

Back to top ↑
Connect with Us

What they says

© 2013 MaGeSH 2 help. WP Mythemeshop Converted by BloggerTheme9
Blogger templates. Proudly Powered by Blogger.