Menus and the Action Bar

Goals

  • Create buttons and icons in the Action Bar
  • Respond to event when user presses a button in the Action Bar

Menus on Android

  • For the course, menus and the Action Bar are the same thing
  • Most (all older) Android devices have a physical menu button
    • Requirement was removed when tablets and Android 3.0 appeared, where the menu button can appear as a virtual button on the screen instead.
  • Therefore, two versions depending on Android version
    • Menu pops up from the bottom of screen (older version, before 3.0)
    • Menu pops down from the so called ActionBar at the top of screen (from 3.0)
  • You can write the same code and the platform will display using the appropriate version

Menu handling

  • Your choice of menu is not specified or set in any call
  • Instead an event is sent to your Activity when it is time to create the menu(s)
  • Menu items (and buttons/icons for the Action Bar) can be created
    • Dynamically in Java code at the time of the event
    • Statically in an XML resource file that is loaded at the time of the event
    • Or even a combination of both
    • We'll only see the XML method in the course

Defining your menu(s)

  • Create XML resource file in menu directory, for instance main.xml
    <menu xmlns:android="http://schemas.android.com/apk/res/android">
      <item android:id="@+id/do_something"
          android:title="@string/do_something_menu_title"
          android:orderInCategory="100"
          android:showAsAction="never" />
    </menu>
    
  • Load in Activity event onCreateOptionsMenu
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    

Display options for the Action Bar items

  • Attributes on item element
    • id is the usual identifier that you use in if statements to responed to the correct choice
    • title should be a string reference for translation purposes
    • orderInCategory is a number that defines the order in which items appear
    • icon is a drawable resource to show instead of the title (or both with "withText")
  • showAsAction
    • always means to always show it on screen (in the Action Bar)
    • never means to only show it in drop down menu
    • ifRoom means to try and show it on screen if width allows
    • withText displays both icon and title if both present

Responding to menu selection

  • Event sent to Activity when user has chosen an option
    @Override
    boolean onOptionsItemSelected(MenuItem item) {
      if (item.getItemId()==R.id.do_something) {
        doSomething();
        return true;
      }
      return false;
    }
    

More information

  • Book references
    • Android Programming Unleashed, Chapter 7 Creating Interactive Menus and ActionBars, Creating Menus Through Coding