Home  >  Android

Android Options Menu Example using getMenuInflater().inflate, onCreateOptionsMenu and onOptionsItemSelected

By Arvind Rai, August 04, 2015
This page will walk through Android options menu example using getMenuInflater().inflate, onCreateOptionsMenu and onOptionsItemSelected. Options menu is the primary collection of menu items. Other menu types are Context menu which displays on long click on an element and Popup menu which displays a list of items in vertical list. Before Android 3, options menu is displayed by clicking menu button. In Android 3 and later, options menu is shown in action bar. Menu item can be search, save, print, delete, bookmark etc. To create menu we have to override onCreateOptionsMenu, in which we use getMenuInflater().inflate that inflates a menu hierarchy from XML resource. To handle click event, override onOptionsItemSelected in Activity class. We are providing here a complete example for options menu.

Create Menu Item in XML

Create menu Item in XML file within res/menu.
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/bookmark_menu" 
          android:title="@string/bookmark"
          android:showAsAction="ifRoom"/>
</menu> 

<menu>: Root node that contains one or more item.
<item>: It represents menu items.
android:id: Unique ID for the item.
android:title : Title for the item.
android:showAsAction : It specifies how an item to be shown as an action item. The value can be ifRoom, never, withText, always, collapseActionView.


No Menu Button Starting from Android 3.0 (Honeycomb)

Starting from Android 3.0 (Honeycomb) , there is no menu button, find the link.

Say Goodbye to the Menu Button

Menu icon is set by the item attribute android:icon="@drawable/ic_save" .

Override onCreateOptionsMenu and use getMenuInflater().inflate

Find the onCreateOptionsMenu(Menu menu) method which needs to override in Activity class. This creates menu and returns Boolean value. inflate inflates a menu hierarchy from XML resource.
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

Override onOptionsItemSelected(MenuItem item) to Handle Click Event

To handle click event on menu item, we have to implement onOptionsItemSelected(MenuItem item) in Activity class and return Boolean value. For the demo we are using Toast to display click event.
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
	        case R.id.bookmark_menu:
	            Toast.makeText(this, "You have selected Bookmark Menu", Toast.LENGTH_SHORT).show();
	            return true;
        }
    }

Complete Example

Find the complete example.
MainActivity.java
package com.concretepage;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
	        case R.id.bookmark_menu:
	            Toast.makeText(this, "You have selected Bookmark Menu", Toast.LENGTH_SHORT).show();
	            return true;
	        case R.id.save_menu:
	            Toast.makeText(this, "You have selected Save Menu", Toast.LENGTH_SHORT).show();
	            return true;
	        case R.id.search_menu:
	            Toast.makeText(this, "You have selected Search Menu", Toast.LENGTH_SHORT).show();
	            return true;
	        case R.id.share_menu:
	            Toast.makeText(this, "You have selected Share Menu", Toast.LENGTH_SHORT).show();
	            return true;
	        case R.id.delete_menu:
	            Toast.makeText(this, "You have selected Delete Menu", Toast.LENGTH_SHORT).show();
	            return true;
	        case R.id.print_menu:
	            Toast.makeText(this, "You have selected Print menu", Toast.LENGTH_SHORT).show();
	            return true;
	        default:
	            return super.onOptionsItemSelected(item);
	        }
    }    
} 

res/menu/main.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/bookmark_menu" 
          android:title="@string/bookmark"
          android:showAsAction="ifRoom"/>
    <item android:id="@+id/save_menu" 
          android:title="@string/save"
          android:showAsAction="ifRoom"/>
    <item android:id="@+id/search_menu"
          android:title="@string/search"
          android:showAsAction="ifRoom"/>
    <item android:id="@+id/share_menu"
          android:title="@string/share"
          android:showAsAction="ifRoom"/>
    <item android:id="@+id/delete_menu" 
          android:title="@string/delete"
          android:showAsAction="ifRoom"/>  
    <item android:id="@+id/print_menu" 
          android:title="@string/print"
          android:showAsAction="ifRoom"/> 
</menu> 

res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#C98C00"
    tools:context=".MainActivity">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/message" 
        android:textSize="25sp"/>
</LinearLayout> 

res/values/strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">Concrete Page</string>
    <string name="message">Click on menu for Menu Demo</string>     
    <string name="bookmark">Bookmark</string>
    <string name="save">Save</string>
    <string name="search">Search</string>
    <string name="share">Share</string>
    <string name="delete">Delete</string>
    <string name="print">Print</string>                
</resources>  

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.concretepage"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk android:minSdkVersion="16"/>
    <application
        android:allowBackup ="false"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity  android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest> 

Output

Find the screenshot of the output.
We observe that some menu item are in action bar, this is because we have used android:showAsAction="ifRoom" as an item attribute.

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us