Android Options Menu Example

Android Options Menu

The options menu is the primary collection of menu items for an activity. It’s where you should place actions that have a global impact on the app, such as “Search” “Compose email” and “Settings.”

You can declare items for the options menu from either your Activity subclass or a Fragment subclass.

If both your activity and fragment(s) declare items for the options menu, they are combined in the UI. The activity’s items appear first, followed by those of each fragment in the order in which each fragment is added to the activity.

In this article, we will talk about how to add options menu in our application.

In this article, we are creating a simple menu with 4 menu items. On clicking on a single menu item a simple Toast message will be shown.

Creating Menu File

In android, to define options menu, we need to create a new folder menu inside of our project resource directory (res/menu/) and add a new XML (menu_example.xml) file to build the menu.

Following is the example of defining a menu in XML file (menu_example.xml).

menu_example.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/item1"
        android:title="Item 1" />
    <item
        android:id="@+id/item2"
        android:title="Item 2" />
    <item
        android:id="@+id/item3"
        android:title="Item 3"
        app:showAsAction="withText" />

</menu>

Options Menu Attributes

Following are the some commonly used attributes related to options menu control in android applications.

android:id  

It is used to uniquely identify element in application.

android:icon

It is used to set the item’s icon from drawable folder.

android:title

It is used to set the item’s title

android:showAsAction

It is used to specify how the item should appear as an action item in the app bar.It contains the following values:

ifRoom : Only place this item in the app bar if there is room for it.

always : Always place this item in the app bar. Avoid using this unless it’s critical that the item always appear in the action bar. Setting multiple items to always appear as action items can result in them overlapping with other UI in the app bar.

never: Never place this item in the app bar. Instead, list the item in the app bar’s overflow menu.

withText : Also include the title text (defined by android:title) with the action item. 

For information about all the supported attributes, see the Menu Resource document.

Loading Options Menu from an Activity

To specify the options menu for an activity, we need to override onCreateOptionsMenu() method.

In this method, you can inflate your menu resource (defined in XML) into the Menu provided in the callback.

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_example,menu);
    return true;
}

If you observe above code we are calling our menu using MenuInflater.inflate() method in the form of R.menu.menu_file_name. Here our xml file name is menu_example.xml.

Handling Click Events

In android, we can handle options menu item click events using onOptionsItemSelected() method.

When the user selects an item from the options menu (including action items in the app bar), the system calls your activity’s onOptionsItemSelected() method.

This method passes the MenuItem selected.

You can identify the item by calling getItemId(), which returns the unique ID for the menu item (defined by the android:id attribute). You can match this ID against known menu items to perform the appropriate action.

Following is the example of handling options menu item click event using onOptionsItemSelected().

@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    int id = item.getItemId();
    switch (id){
        case R.id.Item1:
            //do something
            return true;
        case R.id.Item2:
            //do something             
             return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

When you successfully handle a menu item, return true.

If you don’t handle the menu item, you should call the superclass implementation of onOptionsItemSelected() (the default implementation returns false).

Creating New Project

1.Create a new project in Android Studio from File ⇒ New Project and fill the project details.

2.Now create a new folder menu inside of our project resource directory (res/menu/) and add a new XML (menu_main.xml) file to build the menu.

3.Open newly created xml (menu_main.xml) file and write the code as shown below.

menu_main.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/Item1"
        android:title="Item1" />

    <item
        android:id="@+id/Item2"
        android:title="Item2" />

    <item
        android:id="@+id/Item3"
        android:title="Item3" />

    <item
        android:id="@+id/Item4"
        android:title="Item4" />


</menu>

4.Now open MainActivity.Java and type following code. In the following code each menu item is identified by its ID in switch case statement.

MainActivity.java

package com.example.optionmenudemo;

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }
// Initiating Menu XML file (menu_main.xml)
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_main, menu);
        return true;
    }
/**
*Event handling for individual menu item selected
*identify single menu item by its ID
*/
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case R.id.Item1:
                Toast.makeText(getApplicationContext(), "Item1 Selected ", Toast.LENGTH_LONG).show();
                return true;
            case R.id.Item2:
                Toast.makeText(getApplicationContext(), "Item2 Selected ", Toast.LENGTH_LONG).show();
                return true;
            case R.id.Item3:
                Toast.makeText(getApplicationContext(), "Item3 Selected ", Toast.LENGTH_LONG).show();
                return true;
            case R.id.Item4:
                Toast.makeText(getApplicationContext(), "Item4 Selected ", Toast.LENGTH_LONG).show();
                return true;

            default:
                return super.onOptionsItemSelected(item);
        }
    }
}

When we run above example using android virtual device (AVD) we will get a result like as shown below.

abcd

Options Menu with Icon

You need to have icon images inside the res/drawable directory. The android:icon element is used to display the icon on the options menu.

menu_main.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/Item1"
        android:icon="@android:drawable/ic_menu_share"
        android:title="Item1"
        app:showAsAction="always" />

    <item
        android:id="@+id/Item2"
        android:icon="@android:drawable/ic_menu_camera"
        android:title="Item2"
        app:showAsAction="ifRoom" />

    <item
        android:id="@+id/Item3"
        android:icon="@android:drawable/ic_menu_search"
        android:title="Item3"
        app:showAsAction="never" />

    <item
        android:id="@+id/Item4"
        android:icon="@android:drawable/ic_menu_add"
        android:title="Item4"
        app:showAsAction="withText" />


</menu>

When you run your application after adding the above menu_main.xml it will look like this:

Screenshot_1574334747        Screenshot_1574334751

I hope this article will help you in understanding how to create Options Menu to handle global functionalities in our applications.

 

Leave a Reply