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


    
        Tools
        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();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
...

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

@Override
public boolean onCreateOptionsMenu(Menu menu) 
{
   getSupportMenuInflater().inflate(R.menu.actionbar_menu, menu);
            
   SpinnerAdapter mSpinnerAdapter;
   if(Build.VERSION.SDK_INT <= 10) 
   {
      mSpinnerAdapter = ArrayAdapter.createFromResource(this, R.array.nav_list,android.R.layout.simple_spinner_item);
   }
   else
   {
      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);

      @Override
      public boolean onNavigationItemSelected(int position, long itemId) 
      {
         switch (position)
         {
             case 1:
                 Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://developer.android.com/design/index.html"));
                 startActivity(browserIntent);
                 break;
             case 2:
                 openPlayStore();
                 break;
          }
                  
          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.