237
Chapter 10: Going a la Carte with Your Menu
The Task Reminder application needs a mechanism in which to delete a task when it is no longer needed in the app. I am going to implement the 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.
Creating the menu XML file
To create this menu, create a new XML file in the resmenu 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.comapkresandroid” item android:id=”+idmenu_delete”
android:title=”stringmenu_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 I do not have an icon associated with this menu. This is because a context menu does not
support icons because they are simply a list of menu options that floats above the current activity.
Loading the menu
To load the menu, type the following code into the onCreateContextMenu method:
Override public void onCreateContextMenuContextMenu menu, View v,
ContextMenuInfo menuInfo { super.onCreateContextMenumenu, v, menuInfo;
MenuInflater mi = getMenuInflater; mi.inflateR.menu.list_menu_item_longpress, menu;
}
This code performs the same function as the onCreateOptionsMenu call, but this time you are inflating the menu for the context menu and you are
loading the context menu. Now, if you long-press a list item in the list view, you receive a context menu, as shown in Figure 10-2.
238
Part III: Creating a Feature-Rich Application
Figure 10-2:
The context menu in
the Task Reminder
application.
Handling user selections
Handling the selection of these menu items is very similar to an option menu as well. To handle the selection of the context menu, type the following code
into the bottom of your class file:
Override public boolean onContextItemSelectedMenuItem item {
➝
2 switchitem.getItemId {
➝
3 case R.id.menu_delete:
➝
4 Delete the task
return true; }
return super.onContextItemSelecteditem; }
The code lines are explained here:
➝
2 This is the method that is called when a context menu item is
selected. The item parameter is the item that was selected in the context menu.
➝
3
A switch statement is used to determine which item was clicked based upon the ID as defined in the list_menu_
item_longpress.xml file.
239
Chapter 10: Going a la Carte with Your Menu