You can use a number of options to customize and control the action bar. These options allow you to control certain aspects of the action bar such as displaying the application logo instead of the icon, showing the title, and using a custom view. The following list describes the supported display options:
DISPLAY_SHOW_CUSTOM—Show the custom view, if one has been set.
DISPLAY_SHOW_HOME—Show home elements, leaving more space for other navi- gation elements.
DISPLAY_HOME_AS_UP—Display the application home icon with the up indicator.
DISPLAY_SHOW_TITLE—Show the Activity title and, if present, subtitle.
DISPLAY_USE_LOGO—Use a logo instead of an icon, if available.
Together with these options, the ActionBar class also provides a number of methods to manipulate them (see table 21.2).
Table 21.2 Action bar display options methods
Action bar method Description
void setDisplayOptions(int options) Set several display options at once. You can select one or more options by ORing them together.
void setDisplayOptions(
int options, int mask)
Specified display options that match the mask are set; others are unset.
int getDisplayOptions() Return the current set of display options.
void setDisplayShowCustomEnabled(
boolean showCustom)
Helper method. This is the same as calling setDisplayOptions() with
DISPLAY_SHOW_CUSTOM.
void setDisplayShowHomeEnabled(
boolean showHome)
Helper method. This is the same as calling setDisplayOptions() with
DISPLAY_SHOW_HOME.
void setDisplayHomeAsUpEnabled ( boolean showHome)
Helper method. This is the same as calling setDisplayOptions() with
DISPLAY_HOME_AS_UP. void setDisplayShowTitleEnabled(
boolean showTitle)
Helper method. This is the same as calling setDisplayOptions() with
DISPLAY_SHOW_TITLE.
void setDisplayUseLogoEnabled(
boolean useLogo)
Helper method. This is the same as calling setDisplayOptions() with
DISPLAY_USE_LOGO.
Table 21.2 is self-explanatory, but as you can see there are two kinds of display option methods: helper methods to set/unset a specific kind of display option, and the generic setDisplayOptions(…) to manipulate multiple options at once via an input bitmask. The following two listings show two examples of how to set display options using the bitmask methods and the helper methods.
ActionBar bar = getActionBar();
if (bar != null) {
bar.setDisplayOptions(
ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_SHOW_HOME);
}
Listing 21.3 calls the setDisplayOptions() method to set two specific display options:
the application (home) icon as “navigate up” and the ShowHome option. Using the bit- mask method allows you to manipulate multiple settings at once. Listing 21.4 is similar to listing 21.3 but instead calls the helper methods directly.
ActionBar bar = getActionBar();
if (bar != null) {
bar.setDisplayShowHomeEnabled(true);
bar.setDisplayHomeAsUpEnabled(true);
}
Although the ShowHome option is intended to maximize the space available in the action bar (by showing the icon or logo and removing items such as the application name), the DisplayHomeAsUp option adds a visual up indicator to the icon or logo, as shown in figure 21.3.
It’s good practice to enable the DisplayHomeAsUp indicator when you make the application icon an action item to navigate up or
back. The visual indicator provides a hint to the user about such behavior if they click the application icon. We’ll cover the application icon as an action item later, in section 21.4.1.
The following sections cover each part of the action bar and the related API, starting with the application name and icon.
21.3.1 Application name and icon
All Android applications have a name or title and an icon. Starting with Android 3.0, applications can also have a wider logo in place of the standard icon. On the action bar, the two leftmost members are the application icon and title, as illustrated in figure 21.4.
Listing 21.3 Setting the ActionBar display options using the generic method
Listing 21.4 Setting the ActionBar display options using the helper methods
Figure 21.3 The application icon as a “navigate up” (left, as shown in Android 3.0–3.1; right, Android 3.2)
The application name and icon (and logo) are defined as usual, in the manifest file (AndroidManifest.xml), as shown in the following listing.
<application
android:icon="@drawable/manningicon"
android:label="@string/app_name"
android:logo="@drawable/manninglogo">
When you’ve defined these attributes, the application icon and name appear on the action bar. You can control the appearance of the action bar by setting one or more display options, as previously covered.
The next element on the action bar is either the navigation list or navigation tabs.
21.3.2 Navigation modes
To the right of the application icon and name/title is the navigation list or navigation tabs, as illustrated in figure 21.5.
The navigation to display (none, list, or tabs) depends on the navigation mode that is selected. Modes are mutually exclusive, with one of three navigation modes set at any given time:
NAVIGATION_MODE_STANDARD—The standard navigation mode with no drop- down list or tab navigation. It supports standard DisplayHomeAsUp, action, and menu items.
NAVIGATION_MODE_LIST—In addition to standard navigation, adds list-based navigation such as a drop-down list.
NAVIGATION_MODE_TABS—In addition to standard navigation, adds tabs-based navigation (for fragments).
Similar to the display options, the action bar provides a number of navigation option- related methods (see table 21.3). Using these methods, you can set the navigation mode for the action bar, set an event listener, get the count of navigation items, and so on.
Listing 21.5 Specifying the application name and icon Figure 21.4 Application icon and title/name
Figure 21.5 The navigation tabs (or list)
When working with the action bar, the first thing the Activity should do is to set the navigation mode. The following listing shows how to set the navigation mode to tabs- based navigation.
ActionBar bar = getActionBar();
if (bar != null) {
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
}
In addition to setting the navigation mode, you must define the tabs or list as appro- priate and related artifacts such as adapters and listeners. The next sections will cover tab and list navigation in more detail.
TAB NAVIGATION
When defined, tabs are located to the right of the application icon or logo and title, as illustrated in figure 21.6.
The action bar provides support for tab-based navigation that allows activities to navigate across fragments. Associated fragments must be defined in the Activity lay- out, as covered in chapter 20. Tabs can have a title, an icon, or both. When a tab selec- tion is made, a tab listener receives the corresponding tab events. As part of the tab
Table 21.3 Action bar navigation mode methods
Action bar method Description
void setNavigationMode(int mode) Set the current navigation mode.
void setListNavigationCallbacks(SpinnerAdapter adapter, ActionBar.OnNavigationListener callback)
Set the adapter and navigation call- back for list-navigation mode.
int getNavigationMode() Get the current navigation mode.
void setSelectedNavigationItem(int position) Select the specified navigation item.
int getNavigationItemCount() Get the number of navigation items in the current navigation mode.
int getSelectedNavigationIndex() Get the position of the selected navi- gation item in list or tabbed naviga- tion mode.
Listing 21.6 Setting the navigation mode to use tabs
Figure 21.6 Action bar tab navigation
event listener, a fragment transaction is automatically initiated by the system, allowing the listener to add or remove fragments as needed. Tab events can also be used to set state for a given fragment: for example, you can use tabs as a way to select the current category to display on the current fragment.
ActionBar provides a number of methods to instantiate tabs, add and remove tabs, and listen for tab events; see table 21.4.
After the navigation mode has been set, you call newTab() to create a new tab, set- Text() to set its text or title, setIcon() to set the icon displayed with the tab, setTab- Listener() to set the tab listener, and addTab() to add the tab to the action bar. You can also define a custom view by calling setCustomView() to be used for the tab. The following listing shows how to set up a basic tab.
private String[] mCategories = new String[] { "Technology",
"Sports", "Arts"};
...
ActionBar bar = getActionBar();
if (bar != null) {
bar.setDisplayShowTitleEnabled(false);
bar.setNavigationMode(ActionBar. NAVIGATION_MODE_TABS);
for (int i=0; i<mCategories.length; i++) {
bar.addTab(bar.newTab().setText(mCategories[i]).
➥setTabListener(this));
Table 21.4 Action bar tab navigation methods
Action bar method Description
ActionBar.Tab getSelectedTab() If in tabbed navigation mode, return the currently selected tab.
void addTab(ActionBar.Tab tab)
void addTab(ActionBar.Tab tab, boolean setSelected)
void addTab(ActionBar.Tab tab, int position) void addTab(ActionBar.Tab tab, int position,
boolean setSelected)
Add a tab to the action bar.
ActionBar.Tab newTab() Create and return a new ActionBar.Tab.
void removeAllTabs() Remove all tabs from the action bar.
void removeTab(ActionBar.Tab tab) Remove a tab from the action bar.
void removeTabAt(int position) Remove a tab from the action bar.
void selectTab(ActionBar.Tab tab) Select the specified tab, adding it to the action bar if needed.
Listing 21.7 Setting up tab navigation
Set navigation mode to tabs
B
Create and add tabs
C
}
bar.setDisplayOptions(
ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_SHOW_HOME);
}
In listing 21.7, we set a couple of display options: in order to maximize the space avail- able in the action bar, we don’t show the application title; and we set the navigation to tab-based B. Next, we instantiate the tabs C and add them to the action bar. Finally, we set some additional display options to enable the application icon for navigation.
Next, you need to listen for tab events. For this you must implement a tab listener that will receive tab events when a given tab is added or deleted, receives focus, or gets unfocused. The ActionBar.TabListener interface defines the listener methods in table 21.5.
The following listing shows an example of an action bar tab listener.
public class MainActivity extends Activity implements ActionBar.TabListener {
:
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) { SummaryListFragment frag = (SummaryListFragment)
getFragmentManager().findFragmentById(R.id.frag_summary_listview);
frag.setCategory(tab.getPosition());
}
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
...
}
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
...
} }
Table 21.5 Action bar tab listener methods
ActionBar.TabListener methods Description
void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft)
Called when a tab enters the selected state
void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft)
Called when a tab exits the selected state
void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft)
Called when a tab that is already selected is chosen again by the user
Listing 21.8 Action bar tab listener
In this listing, when a tab is selected, we add new fragments or select the fragment for which to set the fragment state. When a tab is unselected, the appropriate cleanup code executes. When the tab is reselected, we refresh the tab as appropriate or do nothing.
All the tab methods take two parameters: the selected tab and a fragment transac- tion to use. Within the fragment transaction, you add, remove, or change fragments.
Don’t commit fragments via ft.commit(), because the system will commit the frag- ment transaction automatically; for more information about fragments and transac- tions, see chapter 20. Fragments can’t be added to the back stack; to learn more about fragments and the back stack, again see chapter 20.
If you don’t want to use tab-based navigation in your application, you can use list navigation, which is covered next.
LIST NAVIGATION
Instead of the tab navigation, you can use a drop-down list navigation that consists of a simple list. The list is located at the same place where the tab would be: to the right of the application icon and title (see figure 21.7).
As with the other types of navigation, the setNavigationMode() method must be called to set the list navigation mode.
ActionBar bar = getActionBar();
if (bar != null) {
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
}
To set up list navigation, a list navigation callback must be set by calling the action bar method setListNavigationCallbacks(). This method takes two arguments: a source adapter, which in this example is an ArrayAdapter that provides access to the list data items to display; and an OnNavigationListener to receive list navigation events. This is shown in the following listing.
private String[] mCategories = new String[] { "Technology",
"Sports",
Listing 21.9 Setting the list navigation mode
Listing 21.10 Setting up list navigation Figure 21.7 Action bar drop-down list navigation
Define array with data to display in list
B
"Arts"};
: :
ArrayAdapter<String> navListAdapter = new ArrayAdapter<String>(
this,
R.layout.spinner_textview, mCategories);
bar.setListNavigationCallbacks(navListAdapter, new OnNavigationListener() {
@Override
public boolean onNavigationItemSelected(int position, long itemId) { Toast.makeText(MainActivity.this,
"onNavigationItemSelected: " + position, Toast.LENGTH_LONG).show();
return true;
} });
Listing 21.10 also defines a simple array of strings as the data source B. List-based nav- igation uses an Adapter for its data, and this example uses a simple ArrayAdapterC. To be notified when an item in the list is selected, we define a list event callback D;
here we identify the appropriate fragment to work with based on the onNavigation- ItemSelected(intposition,longitemId) parameters. This example does a Toast when a list item has been selected.
When an event occurs, the event listener method onNavigationItemSelected() is called, passing the position and ID of the selected item. You display the appropriate fragment or set the proper fragment state based on the list selection.
As we continue moving down the action bar, the next elements to the right are action items, covered next.