Home > Articles > Mobile Application Development & Programming

  • Print
  • + Share This
From the author of Customizing Your Action Bar

Customizing Your Action Bar

Once your application is targeting the Honeycomb platform, you can really start to take advantage of what the action bar widget has to offer by placing your option menu items right on the action bar to make things easier for the user. The primary menu item attribute that controls this behavior is the android:showAsAction attribute.

This attribute can be any of the following values:

  • always: This value will cause the menu item to always be shown on the action bar
  • ifRoom: This value will cause the menu item to be shown on the action bar if there is sufficient room.
  • never: This value will cause the menu item to never be shown on the action bar
  • withText: This value will cause the menu item to be displayed with its icon and its menu text

Let's give this a shot by modifying the options menu resource file to use this attribute in different ways. First, if you look back at Figure 1, this is what the action bar will look like if you set each menu item to display if there's room, along with its name. In other words, each menu item has the following attribute:

android:showAsAction="ifRoom|withText"

Another reasonable setting is to display each menu item on the action bar, provided there is space, but without the clutter of the text. In other words, each menu item has the following attribute:

android:showAsAction="ifRoom"

Figure 5 shows what this change achieves on your typical Honeycomb device.

Figure 5 Showing menu items on the action bar when room is available, including text (Click Image to Enlarge)

Finally, let's say that we never want to see the Vacuum menu item on the action bar.

android:showAsAction="never"

This will result in two menu items on the action bar: Sweep and Scrub. Then, in the far-right corner, you'll see the overflow menu again. Click it to see any menu items set to never (like Vacuum) as well as any other menu items that might not have fit on the action bar (Figure 6).

Figure 6 Showing some menu items on the action bar, while others never show (instead appear in the overflow menu) (Click Image to Enlarge)

<?xml version="1.0" encoding="utf-8"?>
<menu
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/sweep"
        android:icon="@drawable/ic_menu_sweep"
        android:title="@string/sweep" 
        android:onClick="onOptionSweep" />
    <item
        android:id="@+id/scrub"
        android:icon="@drawable/ic_menu_scrub"
        android:title="@string/scrub"
        android:onClick="onOptionScrub" />
    <item
        android:id="@+id/vacuum"
        android:icon="@drawable/ic_menu_vac"
        android:title="@string/vacuum" 
        android:onClick="onOptionVacuum" />
</menu>
  • + Share This
  • 🔖 Save To Your Account