Random thoughts of a warped mind…

July 26, 2011

How to add a dropdown menu in your Android app (Spinner!)

Filed under: All,Android,Android,Development — Srinivas @ 16:27

It took me a while to figure out how to use a “drop down” list in my Android app. Turns out you use the widget called Spinner (http://developer.android.com/reference/android/widget/Spinner.html).

Lets say you have an activity called ExpenseHistory that displays some user information based on a time period selected by the user and time period is what you want to offer as a dropdown menu. Assuming the Layout for this activity is defined in expensehistory.xml, first add a Spinner widget to the layout.

<br /><Spinner android:id='@+id/Dispmodespinner' android:layout_width='120' android:layout_height='wrap_content' android:[email protected]/Dispmode_prompt'><br />

We have added to our layout a Spinner with ID “Dispmodespinner” and prompt option “Dispmode_prompt”. Later in our activitys onCreate() code, we will instantiate a new spinner as “R.id.Dispmodespinner”. So what is Dispmode_prompt? Simple, its an array of values that will be used in the dropdown list e.g Today, Last one week and so on…

In your android project, edit projectname/res/values/strings.xml to add the following into it:

<string-array name='Dispmode_array'><br /><item>Current</item><br /><item>Last 20</item><br /><item>Last 24 hours</item><br /><item>Last 7 days</item><br /></string-array><br />

In the previous listing we have defined an String array that we will parse using an ArrayAdapter to build and associate the spinner with…

In your Activity (ExpenseActivity for example), import the following:

<br />import android.widget.AdapterView;<br />import android.widget.AdapterView.OnItemSelectedListener;<br />import android.widget.ArrayAdapter;<br />import android.widget.Spinner;<br />

Define the following in your Activity Class:

private Spinner dispmode;

Add a private inside class to your activity:

//Private class ItemSelected is used to setup new Spinner items.<br />private class ItemSelected implements OnItemSelectedListener<br />{<br />Boolean Initialized=false;<br />String myName;<br />public ItemSelected(String name){myName=name;}<br />public void onItemSelected(AdapterView<?> parent, View view, int pos, long id)<br />{<br /><%%KEEPWHITESPACE%%>        if(Initialized){<br /><%%KEEPWHITESPACE%%>                Toast.makeText(parent.getContext(), 'Spinner for '+myName+ ' selected Position=' + pos + 'Text='+parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();<br /><br /><%%KEEPWHITESPACE%%>        SharedPreferences.Editor editor1=mprefs.edit();<br /><%%KEEPWHITESPACE%%>        String val=parent.getItemAtPosition(pos).toString();<br /><%%KEEPWHITESPACE%%>        Log.d(TAG,'Saving param '+myName + '['+val+'] to sharedpreferences and setting svrconfigchanged=1');<br /><%%KEEPWHITESPACE%%>        editor1.putString(myName, val);<br /><%%KEEPWHITESPACE%%>        editor1.putString('svrconfigchanged', '1');<br /><%%KEEPWHITESPACE%%>        editor1.commit();}<br /><br /><%%KEEPWHITESPACE%%>        Initialized=true;<br /><%%KEEPWHITESPACE%%>        }<br />public void onNothingSelected(AdapterView parent) {// Do nothing.}}<br />

The class “ItemSelected” implements the OnItemSelectedListener and defines implementations for the methods onItemSelected() and onNothingSelected(). When I was initially playing around with Spinner for my app, I needed to have multiple spinners for different items and I had a problem try to figure out which spinner the user made a choice from. When the user made a selection, I also wanted the app to Toast a message to the screen informing what had been selected. Unfortunately the default examples always led to the Toast message being fired whenever the Spinner got initialized/setup as part of the onCreate() – I did’nt like that. And hence the use of the following:

  • A constructor accepting a String – This would be the “name” of the parameter the user was making a selection for.
  • Use of a Boolean flag to determine if Spinner was being initialized for the first time (so no Toast message) or if a user actually selected an option from the Spinner(then display Toast message).

In the example above, I am saving the selected preference to my apps local preferences – you may want to do something different with it.

Now its time to setup the Spinner in your activitys onCreate(). Add this:

//Define spinner options for Dispmode<br />dispmode=(Spinner) findViewById(R.id.Dispmodespinner);<br />ArrayAdapter<CharSequence> adapter=ArrayAdapter.createFromResource(this, R.array.Dispmode_array, android.R.layout.simple_spinner_item);<br />dispmode.setAdapter(adapter);<br />dispmode.setOnItemSelectedListener(new ItemSelected('dispmode'));<br />

In the above snippet, we did the following:

  • Based on the XML we added into the Layout file, Eclipse added R.id.Dispmodespinner as the ID for the Spinner. We use this to initialize the Spinner dispmode in our code.
  • The string array “Dispmode_array” we had added into strings.xml is available as resource “R.array.Dispmode_array” and we used this to create a new ArrayAdapter instance.
  • We set the spinner to use the values from the newly created ArrayAdapter (These would be the values displayed when the Spinner is expanded by the user).
  • Set the onClick listener for the new spinner to be an instance of “ItemSelected” set with name “dispmode”.

To add a second spinner now(say with name “expensetypes”, all you would need to do is to add a new string array (say “expensetypes_array”to strings.xml, add a Spinner to the layout , setup the Spinner in your onCreate() , create a new ArrayAdapter built from values in “expensetypes_array”, associate the new spinner with this ArrayAdapter and then set the onclick listener for the new spinner to be “new ItemSelected(“expensetypes”)”. Thats it…

  • http://www.lemontravel.pl Biura Turystyczne Gdynia

    I’ll right away take hold of your rss as I can’t find your e-mail subscription hyperlink or newsletter service. Do you’ve any? Kindly permit me know in order that I may just subscribe. Thanks.

  • Srinivas

    Hi, Its http://www.onepwr.org/feed/rss/ . Guess I took out the rss link to make space on the screen ;-)

  • Pingback: servinion()

  • Pingback: URL()

Powered by WordPress