Basic spinner design


SDK Version: 
M3

In android creating spinners - known as comboboxes or Drop-down list in other systems - is easy. However giving them a basic design is a little tricky.

In most application we dont want to add custom design to spinners, but at least we want thicker items in the list. With the default look, people will have trouble hitting the desired item.

The code, one may try at first, to fill a spinner with elements, will probably look like this:

The layout xml 'mylayout.xml':

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent">
  6.  
  7.         <Spinner android:id="@+id/myspinner"
  8.         android:layout_width="wrap_content"
  9.         android:layout_height="wrap_content" />
  10.  
  11. </LinearLayout>

In the Activity oncreate method:

  1. setContentView(R.layout.mylayout);
  2. ArrayAdapter myAdapter = new ArrayAdapter(this,
  3.   android.R.layout.simple_spinner_item,
  4.   new String[]{"one","two","three","four","five"});
  5. Spinner mySpinner = (Spinner) findViewById(R.id.myspinner);
  6. mySpinner.setAdapter(myAdapter);

And this will create a spinner like this:




Now android.R.layout.simple_spinner_item determines the layout of each item, including the design of the currently selcted item. If we change this layout to a customly created thicker one, the spinner displaying the selected item will be thisker too, and will look ugly.

The solution is to use the adapters setDropDownViewResource method which changes only the list design. There is even a built in layout for the spinner items called simple_spinner_dropdown_item.

  1. myAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

The simple_spinner_dropdown_item even includes a dot indication the currently selected element and will look like this:




Have fun!