Search⌘ K

Options, Context, and Popup Menus

Explore how to create and manage options menus, context menus, and popup menus in Android applications. Understand the setup process including defining menu layouts, inflating menus, and attaching event handlers to improve user interaction within your app. Gain practical experience with examples and code snippets to build responsive and functional menus suited for various use cases.

Introduction

In this lesson, we’ll learn about menus in Android. You can create options menus, context menus, and popup menus in your Android apps, and each of these menus serves specific use cases.

Options menu

The options menu is considered the main menu for the activity. It should be used for allowing access to primary functionalities of the activity, such as “Search,” “Settings,” and “Help.” Let’s learn how to create an options menu in an Android app.

Step 1: Define the layout

First, we need to define the layout for the menu containing the menu items, with the title and icon specified. Create a resource file called menu_options_menu.xml in res/menu and add the following contents to it.

XML
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/new_game"
android:icon="@drawable/ic_new_game"
android:title="@string/new_game"
app:showAsAction="ifRoom" />
<item android:id="@+id/help"
android:icon="@drawable/ic_help"
android:title="@string/help" />
</menu>

Notice that we’ve added two menu items to the menu, but we can add more depending on our use case. Also, notice that the first item—the new game—has an app:showAsAction attribute set as ifRoom. It tells Android to show this menu item in the action bar if there’s sufficient space, but otherwise, it shows it in the menu.

Step 2: Inflate the menu

Next, we need to inflate this ...