Thursday, April 25, 2013

Adding a Spinner to ActionbarSherlock

A spinner is a dropdown on the Actionbar (see screenshot in this post).  It is a list of items that perform an action when selected.  It is fairly easy to add to your project using ActionbarSherlock.

There are a few steps to creating the Spinner

  • Create an XML resource file
  • Add Spinner to menu XML
  • Add Actionbar navigation code to onCreate() in the Activity using the Spinner
  • Adding code to handle Spinner items being selected
Create An XML Resource File

In the resource file, the items to be displayed should be listed. The file should be in res/values.  I named the file spinner_resources.xml

        Android Design Guide Site
        Rate This App
Add Spinner to Menu XML

The XML added must reference the ActiobarSherlock Spinner object


Add Navigation Code

In the Activity.onCreate() method, a couple of lines need to be added to get a handle on the Actionbar and to set the navigation mode to list.
actionBar = getSupportActionBar();

Code to Handle Spinner Selection

In the onCreateOptionsMenu() method, the code should

  • inflate the menu
  • add a spinner adapter
  • add a navigation listener to handle spinner selection

public boolean onCreateOptionsMenu(Menu menu) 
   getSupportMenuInflater().inflate(, menu);
   SpinnerAdapter mSpinnerAdapter;
   if(Build.VERSION.SDK_INT <= 10) 
      mSpinnerAdapter = ArrayAdapter.createFromResource(this, R.array.nav_list,android.R.layout.simple_spinner_item);
      mSpinnerAdapter = ArrayAdapter.createFromResource(this, R.array.nav_list,android.R.layout.simple_spinner_dropdown_item);
   OnNavigationListener mOnNavigationListener = new OnNavigationListener() 
      // Get the same strings provided for the drop-down's ArrayAdapter
      //String[] strings = getResources().getStringArray(R.array.nav_list);

      public boolean onNavigationItemSelected(int position, long itemId) 
         switch (position)
             case 1:
                 Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(""));
             case 2:
          return true;
     actionBar.setListNavigationCallbacks(mSpinnerAdapter, mOnNavigationListener);
     return true;

Notice the code that switches the Spinner layout depending on the Android version.

Droid Design Guide is an open source app that has examples of using this feature. The code is in GitHub.

1 comment: