O'Reilly logo

Android™ Tablet Application Development For Dummies® by Donn Felker

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Creating a Context Menu

A context menu is created when a user long-presses a view. The context menu is a floating menu that hovers above the current activity and allows users to choose from various options.

The Task Reminder application needs a mechanism by which to delete a task when it is no longer needed in the app. In this section, you implement this feature as a context menu. Users long-press the task in the list, and they receive a context menu that allows them to delete the task when the context menu is clicked.

Thankfully, creating a context menu is quite similar to creating an option menu. The menu can be defined in XML and can be inflated using the same mechanism that is used in the creation of an options menu. To create a context menu, then, you need to call registerForContextMenu() with a view as the target. You created one of these in Chapter 11. After it is created, you need to override the onCreateContextMenu() call — also demonstrated in Chapter 11.

Creating the menu XML file

To create this menu, create a new XML file in the res/menu directory. I'm going to name mine list_menu_item_longpress.xml. Type the following into the XML file:

<?xml version=“1.0” encoding=“utf-8”?>
<menu
  xmlns:android=“http://schemas.android.com/apk/res/android”>
    <item android:id=“@+id/menu_delete”
          android:title=“@string/menu_delete” />
</menu>

Notice that the title property uses a new string resource menu_delete. You need to create a new string resource with the name of menu_delete

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required