In Android, as I have repeated so many times, there are two ways of creating User Interfaces: writing it in Java code, or in the other hand, using the XML resources. I always use XML as it's the cleanest and most organized method (we can easily create a 3-layers application). So, let's create our Spinner in the XML code.
We go inside the XML file we want to add the spinner in, and we put something like this...
…. <XML-Code> (Layouts, Widgets, Whatever)
<Spinner
android:id="@+id/myspinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:drawSelectorOnTop="true”
android:prompt="Favorite Color" />
…. </XML-Code> (Layouts, Widgets, Whatever)
If we have worked a bit with Android, some of these attributes are well known, attributes like “android:id”, “android:layout_width”... but there is at least one that is new for us:
android:prompt and maybe android:drawSelectorOnTop
android:prompt is just the title of the list of elements. It is a String and can be something like “Chose your color” or “Favorite Color” as I have written above.
android:drawSelectorOnTop in a “true” value, is just indicating that we are going to draw the selector on the top of the view. What is the meaning of this? Maybe playing with this value we can see the effects on the android screen. It's your homework...and mine!
Well once we have defined the Spinner in XML, let's work a bit in Java code:
Spinner hubSpinner = (Spinner) findViewById(R.id.myspinner);
We create a Spinner Class, using the view we created some lines above.
ArrayAdapter adapter = ArrayAdapter.createFromResource( this, R.array.colors , android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
We create an ArrayAdapter to wrap our xml array (Array of colours) and we put some pre-defined styles.
hubSpinner.setAdapter(adapter);
And we set the adapter to the spinner.
Thats all! We have created our first spinner!! Any question or suggestions are welcome!