Android options menu, submenu and menu group example

In this tutorial we will learn how to setup menu, submenu, menu group in Android application using XML layout as well as dynamically adding menu options using code. There are three types of application menus:
  • Options Menu
    • The primary collection of menu items for an activity, which appears when the user touches the MENU button.
  • Context Menu
    • A floating list of menu items that appears when the user touches and holds a view that's registered to provide a context menu.
  • Submenu
    • A floating list of menu items that appears when the user touches a menu item that contains a nested menu.

The easiest way to create a menu is to define the menu in XML layout and then inflate a menu resource during the onCreateOptionsMenu() callback method.
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/start_game"
          android:icon="@drawable/ic_start_game"
          android:title="@string/start_game" />
    <item android:id="@+id/game_help"
          android:icon="@drawable/ic_game_help"
          android:title="@string/game_help" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.game_menu, menu);
    return true;
} 
When the user selects a menu item from the Options Menu the system calls your activity's onOptionsItemSelected() method.This method passes the MenuItem that the user selected. You can identify the menu item by calling getItemId(), which returns the unique ID for the menu item (defined by the android:id attribute in the menu resource or with an integer given to the add() method). You can match this ID against known menu items and perform the appropriate action.

A menu group is a collection of menu items that share certain traits. With a group, you can:

  • Show or hide all items with setGroupVisible()
  • Enable or disable all items with setGroupEnabled()
  • Specify whether all items are checkable with setGroupCheckable()

Dynamically Changing menu items at runtime


Once the activity is created, the onCreateOptionsMenu() method is called only once, as described above. The system keeps and re-uses the Menu you define in this method until your activity is destroyed. If you want to change the Options Menu any time after it's first created, you must override the onPrepareOptionsMenu() method. This passes you the Menu object as it currently exists. This is useful if you'd like to remove, add, disable, or enable menu items depending on the current state of your application.

This example only deals with Options menu and Submenu only. Sample code helps you understand the Menu life cycle and how to create menus using XML layout and programmatically using code for adding and removing menus dynamically.


Options Menu Layout optionmenu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/menu1" android:alphabeticShortcut="a"
        android:title="Menu No. 1" android:orderInCategory="1" />
    <item android:id="@+id/menu2" android:alphabeticShortcut="b"
        android:title="Menu No. 2" android:orderInCategory="2">
        <menu >
        <group android:id="@+id/group2" android:checkableBehavior="single">
            <item android:id="@+id/submenu1" android:title="SubMenu No. 1" />
            <item android:id="@+id/submenu2" android:title="SubMenu No. 2" />
        </group>   
        </menu>
    </item>
</menu>

Android activity explaining various aspects of the menu creation

package com.as400samplecode;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.SubMenu;
import android.widget.Toast;

public class AndroidMenu extends Activity {
   
    private static final int MENU3 = 1;
    private static final int MENU4 = 2;
    private static final int SUBMENU1 = 3;
    private static final int SUBMENU2 = 4;
    private static final int SUBMENU3 = 5;
    private static final int GROUP1 = 6;
    private static final int MENU5 = 7;
    private static final int MENU6 = 8;
   
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        Log.w("ANDROID MENU TUTORIAL:", "onCreate(Bundle savedInstanceState)");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
    }
       
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
       
        Log.w("ANDROID MENU TUTORIAL:", "onCreateOptionsMenu(Menu menu)");
       
        MenuItem menu3 = menu.add(Menu.NONE, MENU3, 3, "Menu No. 3");
         menu3.setAlphabeticShortcut('c');
     
        SubMenu menu4 = menu.addSubMenu(Menu.NONE, MENU4, 4,"Menu No. 4");
        menu4.add(GROUP1, SUBMENU1, 1, "SubMenu No. 1");
        menu4.add(GROUP1, SUBMENU2, 2, "SubMenu No. 2");
        menu4.setGroupCheckable(GROUP1,true,true);
       
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.optionsmenu, menu);
        return true;

    }
   
   

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
       
        Log.w("ANDROID MENU TUTORIAL:", "onPrepareOptionsMenu(Menu menu)");
        MenuItem menu5 = menu.findItem(MENU5);
        if(menu5 == null){
            menu5 = menu.add(Menu.NONE, MENU5, 5, "Menu No. 5");
        }
        MenuItem menu6 = menu.findItem(MENU6);
        if(menu6 == null){
            menu6 = menu.add(Menu.NONE, MENU6, 5, "Menu No. 6");
        }
       
        MenuItem menu2 = menu.findItem(R.id.menu2);
        SubMenu subMenu2 = menu2.getSubMenu();
       
        MenuItem subMenuItem3 = menu.findItem(SUBMENU3);
        if(subMenuItem3 == null){
        subMenu2.add(R.id.group2, SUBMENU3, 3, "SubMenu No. 3");
        subMenu2.setGroupCheckable(R.id.group2,true,true);
        }
       
        return true;
   
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
       
        Log.w("ANDROID MENU TUTORIAL:", "onOptionsItemSelected(MenuItem item)");
       
        // Handle item selection
        switch (item.getItemId()) {
        case R.id.menu1:
            Toast.makeText(this, "Clicked: Menu No. 1", Toast.LENGTH_SHORT).show();
            return true;
        case R.id.menu2:
            Toast.makeText(this, "Clicked: Menu No. 2", Toast.LENGTH_SHORT).show();
            return true;   
        case R.id.submenu1:
            if (item.isChecked()) item.setChecked(false);
            else item.setChecked(true);
            Toast.makeText(this, "Clicked: Menu No. 2 - SubMenu No .1", Toast.LENGTH_SHORT).show();
            return true;
        case R.id.submenu2:
            if (item.isChecked()) item.setChecked(false);
            else item.setChecked(true);
            Toast.makeText(this, "Clicked: Menu No. 2 - SubMenu No .2", Toast.LENGTH_SHORT).show();
            return true;  
        case MENU3:
            Toast.makeText(this, "Clicked: Menu No. 3", Toast.LENGTH_SHORT).show();
            return true;
        case SUBMENU1:
            if (item.isChecked()) item.setChecked(false);
            else item.setChecked(true);
            Toast.makeText(this, "Clicked: Menu No. 4 - SubMenu No .1", Toast.LENGTH_SHORT).show();
            return true;   
        case SUBMENU2:
            if (item.isChecked()) item.setChecked(false);
            else item.setChecked(true);
            Toast.makeText(this, "Clicked: Menu No. 4 - SubMenu No .2", Toast.LENGTH_SHORT).show();
            return true;  
        case SUBMENU3:
            if (item.isChecked()) item.setChecked(false);
            else item.setChecked(true);
            Toast.makeText(this, "Clicked: Menu No. 2 - SubMenu No .3", Toast.LENGTH_SHORT).show();
            return true;   
        default:
            return super.onOptionsItemSelected(item);
        }

    }
   
}

honeycomb android menu example

honeycomb android submenu and group example

No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.