Creating a Context Menu
A context menu appears when a user long-presses a view. The context menu is a floating menu that hovers above the current screen and allows users to choose from various options related to the view they long-pressed.
Thankfully, creating a context menu is quite similar to creating an option menu. You can define the menu in XML and inflate it using the same mechanism that you used when you created the options menu. All you need to do is call registerForContextMenu() with a view as the target. (See Chapter 9 to find out how to create a view as the target.) After you create that, you need to override the onCreateContextMenu() call — also demonstrated in Chapter 9.
The Task Reminder application needs a mechanism in which to delete a task when it’s no longer needed. Users can long-press the task in the list, and a context menu pops up that allows them to delete the task by selecting an item from the menu.
Creating the menu XML file
To create this menu, create a new XML file in the res/menu directory. Name it 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 and the value of Delete Reminder. Also note that you don’t need ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access