Creating and Managing Overflow Menus on Android

From Techotopia
Revision as of 18:06, 1 February 2016 by Neil (Talk | contribs) (Text replacement - "<google>ADSDAQBOX_FLOW</google>" to "<htmlet>adsdaqbox_flow</htmlet>")

Jump to: navigation, search
PreviousTable of ContentsNext
An Android Master/Detail Flow TutorialAnimating User Interfaces with the Android Transitions Framework


<google>BUY_ANDROID</google>


An area of user interface design that has not yet been covered in this book relates to the concept of menus within an Android application. Menus provide a mechanism for providing additional choices to the user beyond the view components that are present in the user interface layout. Whilst there are a number of different menu systems available to the Android application developer, this chapter will focus on the more commonly used Overflow menu.


Contents


The Overflow Menu

The overflow menu (also referred to as the options menu) is a menu that is accessible to the user from the device display and allows the developer to include other application options beyond those included in the user interface of the application. The location of the overflow menu is dependent upon the version of Android that is running on the device. On a device running Android 2.3.3, for example, the overflow menu is represented by the menu icon located in the center (between the back and search buttons) of the bottom soft key toolbar as illustrated in Figure 24-1:


An Android softkey toolbar overflow menu

Figure 24-1


With the Android 4.0 release and later, on the other hand, the overflow menu is located in the top right hand corner (Figure 24-2) in the action toolbar represented by the stack of three squares:


An Android Overflow menu

Figure 24-2


Creating an Overflow Menu

The items in a menu can be declared within an XML file, which is then inflated and displayed to the user on demand. This involves the use of the <menu> element, containing an <item> sub-element for each menu item. The following XML, for example, defines a menu consisting of two menu items relating to color choices:

<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/menu_red"
        android:orderInCategory="1"
        android:showAsAction="never"
        android:title="@string/red_string"/>
	<item
        android:id="@+id/menu_green"
        android:orderInCategory="2"
        android:showAsAction="never"
        android:title="@string/green_string"/>
</menu>

In the above XML, the android:orderInCategory property dictates the order in which the menu items will appear within the menu when it is displayed. The android:showAsAction property, on the other hand, controls the conditions under which the corresponding item appears as an item within the action bar itself. If set to ifRoom, for example, the item will appear in the action bar if there is enough room. Figure 24-3 shows the effect of setting this property to ifRoom for both menu items:


An Android action bar menu item

Figure 24-3


This property should be used sparingly to avoid over cluttering the action bar. By default, a menu XML file is created by Eclipse when a new Android application project is created. This file is located in the res -> menu project folder and contains a single menu item entitled “Settings”:

<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/menu_settings"
        android:orderInCategory="100"
        android:showAsAction="never"
        android:title="@string/menu_settings"/>

</menu>

This menu is already configured to be displayed when the user selects the overflow menu on the user interface when the app is running, so simply modify this one to meet your needs.


Displaying an Overflow Menu

An overflow menu is created by overriding the onCreateOptionsMenu() method of the corresponding activity and then inflating the menu’s XML file. For example, the following code creates the menu contained within a menu XML file named activity_menu_app:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
	getMenuInflater().inflate(R.menu.activity_menu_app, menu);
	return true;
}

As with the menu XML file, Eclipse will already have overridden this method in the main activity of a newly created Android application project. In the event that an overflow menu is not required in your activity, either remove or comment out this method.

Responding to Menu Item Selections

Once a menu has been implemented, the question arises as to how the application receives notification when the user makes menu item selections. All that an activity needs to do to receive menu selection notifications is to override the onOptionsItemSelected() method. Passed as an argument to this method is a reference to the selected menu item. The getItemId() method may then be called on the item to obtain the ID which may, in turn, be used to identify which item was selected. For example:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
	switch (item.getItemId()) {
        case R.id.menu_red:
            // Red item was selected
            return true;
        case R.id.menu_green:
            // Green item was selected
            return true;
        default:
            return super.onOptionsItemSelected(item);
	}
}

Creating Checkable Item Groups

In addition to configuring independent menu items, it is also possible to create groups of menu items. This is of particular use when creating checkable menu items whereby only one out of a number of choices can be selected at any one time. Menu items can be assigned to a group by wrapping then in the <group> tag. The group is declared as checkable using the android:checkableBehavior property, setting the value to either single, all or none. The following XML declares that two menu items make up a group wherein only one item may selected at any given time:

<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<group android:checkableBehavior="single">
    <item
        android:id="@+id/menu_red"
        android:orderInCategory="1"
        android:showAsAction="never"
        android:title="@string/red_string"/>
	<item
        android:id="@+id/menu_green"
        android:orderInCategory="2"
        android:showAsAction="never"
        android:title="@string/green_string"/>
</group>
</menu>

When a menu group is configured to be checkable, a small circle appears next to the item in the menu as illustrated in Figure 24-4. It is important to be aware that the setting and unsetting of this indicator does not take place automatically. It is, therefore, the responsibility of the application to check and uncheck the menu item.

An Android checkable Overflow menu

Figure 24-4


Continuing the color example used previously in this chapter, this would be implemented as follows:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
	switch (item.getItemId()) {
        case R.id.menu_red:
        	if (item.isChecked()) item.setChecked(false);
            else item.setChecked(true);
            mainLayout.setBackgroundColor(android.graphics.Color.RED);
            return true;
        case R.id.menu_green:
        	if (item.isChecked()) item.setChecked(false);
            else item.setChecked(true);
            mainLayout.setBackgroundColor(android.graphics.Color.GREEN);
            return true;
        default:
            return super.onOptionsItemSelected(item);
	}
}

Creating the Example Project

To see the overflow menu in action, begin by launching Eclipse and creating a new Android application project. Name the application and project MenuExample with a package name of com.example.menuexample. Create the project with a blank activity named MenuExampleActivity and the Layout and Fragment named activity_menu_example and fragment_menu_example respectively.


<google>BUY_ANDROID</google>

Modifying the Menu Description

Within the Package Explorer panel, locate the project’s res -> menu -> activity_menu_example.xml file and double click on it to load it into the editing panel. To edit the XML directly, select the activity_menu_example.xml tab located along the bottom edge of the Android Menu panel. Delete the default Settings menu item added by Eclipse and then add new items as a checkable group so that the file reads as follows:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.example.menuexample.MenuExampleActivity" >

   <group android:checkableBehavior="single">
    <item
        android:id="@+id/menu_one"
        android:orderInCategory="1"
        android:showAsAction="never"
        android:title="@string/one_string"/>

	<item
        android:id="@+id/menu_two"
        android:orderInCategory="2"
        android:showAsAction="never"
        android:title="@string/two_string"/>

	<item
        android:id="@+id/menu_three"
        android:orderInCategory="3"
        android:showAsAction="never"
        android:title="@string/three_string"/>
	
	<item
        android:id="@+id/menu_four"
        android:orderInCategory="4"
        android:showAsAction="never"
        android:title="@string/four_string"/>
  </group>
</menu>

Save the file before locating and double-clicking on the res -> values -> strings.xml file. Within the file, add new string resources for the menu options as referenced by the menu items:

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">MenuExample</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
    <string name="one_string">One</string>
    <string name="two_string">Two</string>    
    <string name="three_string">Three</string>    
    <string name="four_string">Four</string>

</resources>

Save and close the strings.xml file before proceeding.

Implementing the onOptionsItemSelected() Method

When items are selected from the menu, the overridden onOptionsItemsSelected() method of the application’s activity will be called. The role of this method will be to identify which item was selected and display a toast message on the screen indicating the selection. Locate and double click on the com.example.menuexample -> src -> MenuExampleActivity.java file and modify the code as follows:


package com.example.menuexample;

import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.widget.Toast;

public class MenuExampleActivity extends Activity {
.
.
.
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		
	  switch (item.getItemId()) {
	        case R.id.menu_one:
	        	if (item.isChecked()) item.setChecked(false);
	            else item.setChecked(true);
	            displayToast("One Selected");
	            return true;
	        case R.id.menu_two:
	        	if (item.isChecked()) item.setChecked(false);
	            else item.setChecked(true);
	        	displayToast("Two Selected");
	            return true;
	        case R.id.menu_three:
	        	if (item.isChecked()) item.setChecked(false);
	            else item.setChecked(true);
	        	displayToast("Three Selected");
	            return true;
	        case R.id.menu_four:
	        	if (item.isChecked()) item.setChecked(false);
	            else item.setChecked(true);
	        	displayToast("Four Selected");
	            return true;
	        default:
	            return super.onOptionsItemSelected(item);
	  }

	}

	void displayToast(String message)
	{
		Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
	}
.
.
}

Testing the Application

Build and run the application on either an emulator or physical Android device. Using the overflow menu, select menu items and verify that the corresponding toast message appears on the display. Note that the currently selected item is displayed as the checked item in the menu.

Summary

On earlier versions of Android, the overflow menu is accessible from the soft key toolbar at the bottom of the screen. On Android 4.0 and later, the menu is accessed from the far right of the actions toolbar at the top of the display. This menu provides a location for applications to provide additional options to the user.

The structure of the menu is most easily defined within an XML file and the application activity receives notifications of menu item selections by overriding and implementing the onOptionsItemSelected() method.


<google>BUY_ANDROID</google>



PreviousTable of ContentsNext
An Android Master/Detail Flow TutorialAnimating User Interfaces with the Android Transitions Framework