Javatpoint Logo
Javatpoint Logo

Android Option Menu Example

Android Option Menus are the primary menus of android. They can be used for settings, search, delete item etc.

Here, we are going to see two examples of option menus. First, the simple option menus and second, options menus with images.

Here, we are inflating the menu by calling the inflate() method of MenuInflater class. To perform event handling on menu items, you need to override onOptionsItemSelected() method of Activity class.

Android Option Menu Example

Let's see how to create menu in android. Let's see the simple option menu example that contains three menu items.

activity_main.xml

We have only one textview in this file.

File: activity_main.xml
File: context_main.xml

menu_main.xml

It contains three items as show below. It is created automatically inside the res/menu directory.

File: menu_main.xml

Activity class

This class displays the content of menu.xml file and performs event handling on clicking the menu items.

File: MainActivity.java

Output:

Output without clicking on the menu button.

android option menu example 1

Output after clicking on the menu button.


android option menu example 2

Output after clicking on the second menu item .


android option menu example 3

Option 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 option menu. You can write the string information in the strings.xml file. But we have written it inside the menu_main.xml file.

File: menu_main.xml
android option menu example 4 android option menu example 5





Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials